java socket demo
Posted zfzf1
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java socket demo相关的知识,希望对你有一定的参考价值。
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(" "); bufferedWriter.flush(); } } catch (IOException e) { e.printStackTrace(); } } }
以上是关于java socket demo的主要内容,如果未能解决你的问题,请参考以下文章
片段:java.lang.RuntimeException:传递结果ResultInfo失败