1,服务端不断轮训创建socket链接,一旦链接成功,启动两个服务端进程,处理服务端的不断接受、和不断发送。
package com.supan; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) throws Exception { ServerSocket server=new ServerSocket(4704); while(true){ Socket socket=server.accept(); if(socket!=null){ System.out.println("客户端已经连接,服务器开启线程处理这个连接。"); new SendThread(socket).start(); new RecevidThread(socket).start(); } } } }
2,发送线程(服务端、客户端的发送)都调用这个
package com.supan; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; /* * 该类主要用于服务端接受本地系统的输入数据,并且发松到客户端 */ public class SendThread extends Thread { private Socket socket; private String line; private BufferedReader is; private PrintWriter os; public SendThread(Socket socket) { this.socket = socket; } public void run() { try { BufferedReader sin = new BufferedReader(new InputStreamReader(System.in)); os = new PrintWriter(socket.getOutputStream()); while (true) { line = sin.readLine(); // 把系统输入的数据放入到socket的输出流中 os.println(line); os.flush(); // 读取socket的输入流并打印出来 } } catch (Exception e) { System.out.println("系统输入数据,和客户端输入数据时出现异常"); } } }
3,接受线程(服务端、客户端的发送)都使用这个
package com.supan; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; /* * 该类主要负责不停的读取客户端传过来的数据,并打印到控制台 */ public class RecevidThread extends Thread { private Socket socket; private String line; private BufferedReader is; private PrintWriter os; public RecevidThread(Socket socket) { this.socket = socket; } public void run() { // 获取socket的输入流 try { is = new BufferedReader(new InputStreamReader( socket.getInputStream())); while (true) { System.out.println("客户端传过来的数据是:" + is.readLine()); } } catch (Exception e) { System.out.println("系统输入数据,和客户端输入数据时出现异常"); } } }
4,客户端接受线程
package com.supan; import java.net.Socket; public class Client { public static void main(String[] args) throws Exception { Socket socket=new Socket("localhost",4704); if(socket!=null){ new SendThread(socket).start(); new RecevidThread(socket).start(); } } }
5,测试步骤:
先打开服务端
再打开客户端
即可进行即时通讯。
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/16548.html