码迷,mamicode.com
首页 > 编程语言 > 详细

java socket demo

时间:2019-10-12 15:53:44      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:try   puts   system   tput   reader   buffered   put   class   line   

public class ServerSocketTest {

    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(9999);
            ExecutorService executorService = Executors.newFixedThreadPool(10);
            while (true) {
                final Socket socket = serverSocket.accept();
                Thread thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                            String str;
                            while ((str = bufferedReader.readLine()) != null) {
                                System.out.println(str);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
                executorService.execute(thread);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

public class ClientSocketTest {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("localhost", 9999);
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));

            String str;
            while ((str = bufferedReader.readLine()) != null) {
                bufferedWriter.write(str);
                bufferedWriter.write("\n");
                bufferedWriter.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  

 

java socket demo

标签:try   puts   system   tput   reader   buffered   put   class   line   

原文地址:https://www.cnblogs.com/zfzf1/p/11661930.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!