首先建立服务器端程序:
1.MyServerSocket.java
package com.test.test; public class MyServerSocket { public static void main(String[] args) { new ServerListener().start(); } }
2.ServerListener.java用于监听端口连接
package com.test.test; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import javax.swing.JOptionPane; public class ServerListener extends Thread { public void run() { try { ServerSocket serverSocket=new ServerSocket(12345); while(true){ Socket socket=serverSocket.accept(); JOptionPane.showMessageDialog(null,"有客户端连接到了12345端口!"); new ChatSocket(socket).start(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
3.ChatSocket.java
package com.test.test; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.Socket; public class ChatSocket extends Thread { Socket socket; public ChatSocket(Socket s){ this.socket=s; } public void out(String out){ try { socket.getOutputStream().write(out.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void run() { int count=0; while(true){ count++; out("loop+"+count); } } }
运行MyServerSocket.java:
打开DOS界面 输入telnet localhost 12345 显示如图:
下面点击确定:
再打开一个客户端输入指令:
可以看出每一个客户端都有一个独立的线程进行处理。
时间: 2024-10-13 07:17:48