我讲楼主的代码改了改,我这边运行通过了,也可以连接多个客户端了
服务端: import java.io.DataInputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket;
public class DOSServer { private static Socket s = null; private static ServerSocket ss = null;
public static void main(String[] args) throws Exception { ss = new ServerSocket(8880); // 这里要有死循环,这样就可以链接多个客户端 while (true) { s = ss.accept(); // 阻塞式的方法,此方法在连接传入之前一直阻塞 // 每链接一个客户端就开启一个新的线程为期服务 new Thread(new ClientThread(s)).start(); System.out.println("客户端已经连接!"); } } }
class ClientThread implements Runnable { private Socket s; private DataInputStream dis;
public ClientThread(Socket s) throws Exception { this.s = s; dis = new DataInputStream(s.getInputStream()); }
public void run() { // 循环接受来自客户端的数据 while (true) { try { String data = dis.readUTF(); System.out.println("客户端数据:" + data); } catch (IOException e) { System.out.println("客户端已经断开连接!"); try { s.close(); dis.close(); } catch (IOException e1) { e1.printStackTrace(); } return;// 如果客户端断开了链接,要结束这个线程 } } } }
客户端:
import java.net.*; import java.io.*;
class DOSClient { public static void main(String[] args) throws Exception { Socket s = new Socket("127.0.0.1", 8880); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); DataOutputStream dos = new DataOutputStream(s.getOutputStream()); String data = ""; //循环想服务端输出数据 while (true) { System.out.println("请输入:"); data = br.readLine(); //如果输入exit,结束当前客户端 if (data.equals("exit")) { s.shutdownOutput(); br.close(); dos.close(); return; } dos.writeUTF(data); }
} }
|