这期内容当中小编将会给大家带来有关Java项目中的多线程通信如何利用Socket实现,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
Java Socket实现多线程通信的方法,代码如下:
package com.googlecode.garbagecan.test.socket.sample2; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class MyServer { public static void main(String[] args) throws IOException { ServerSocket server = new ServerSocket(10000); while (true) { Socket socket = server.accept(); invoke(socket); } } private static void invoke(final Socket client) throws IOException { new Thread(new Runnable() { public void run() { BufferedReader in = null; PrintWriter out = null; try { in = new BufferedReader(new InputStreamReader(client.getInputStream())); out = new PrintWriter(client.getOutputStream()); while (true) { String msg = in.readLine(); System.out.println(msg); out.println("Server received " + msg); out.flush(); if (msg.equals("bye")) { break; } } } catch(IOException ex) { ex.printStackTrace(); } finally { try { in.close(); } catch (Exception e) {} try { out.close(); } catch (Exception e) {} try { client.close(); } catch (Exception e) {} } } }).start(); } }
下面是Client程序代码:
package com.googlecode.garbagecan.test.socket.sample2; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; public class MyClient { public static void main(String[] args) throws Exception { Socket socket = new Socket("localhost", 10000); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (true) { String msg = reader.readLine(); out.println(msg); out.flush(); if (msg.equals("bye")) { break; } System.out.println(in.readLine()); } socket.close(); } }
测试,首先运行MyServer类,然后运行两个MyClient类,然后分别在每个MyClient的提示符下输入字符串,就可以看到Server可以分别接收处理每个Client的请求了。
上述就是小编为大家分享的Java项目中的多线程通信如何利用Socket实现了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。