Server端:import java.net.*;
import java.io.*;
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);
s = ss.accept(); //阻塞式的方法,此方法在连接传入之前一直阻塞
ClientThread ct = new ClientThread(s);
new Thread(ct).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 str1;
str1 = dis.readUTF();
System.out.println(str1);
} catch (IOException e) {
e.printStackTrace();
}
//DataOutputStream dos = new DataOutputStream(s.getOutputStream());
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//String str2 = "Server: " + br.readLine();
//dos.writeUTF(str2);
}
}
}
Client端:
import java.net.*;
import java.io.*;
public class DOSClient {
public static void main (String[] args) throws Exception {
Socket s = new Socket("127.0.0.1", 8880);
while (true) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str1 = "Client: " + br.readLine();
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(str1);
//DataInputStream dis = new DataInputStream(s.getInputStream());
//String str2 = dis.readUTF();
//System.out.println(str2);
}
}
}
提问:为什么Server端只能连接一个Client端 |
|