1
我是java網絡編程的新手,所以請記住。服務器客戶端通信凍結`[命令提示符]
我嘗試開發一個多線程的java服務器客戶端應用程序。對於初學者,我旨在僅在單個客戶端和服務器之間開發通信通道。沒有線程之間的單個客戶端服務器之間的通信工作正常。當我申請線程時程序失敗。消息未被髮送。
MyServer.java
class MyServer {
public static void main(String[] args) {
try {
ServerSocket svc = new ServerSocket(4567);
System.out.println("Server Waiting at Port 4567");
do {
Socket sock = svc.accept();
MyServerThread thread = new MyServerThread(sock);
}while(true);
}
catch(UnknownHostException ex) {
System.out.println("Unknown Host");
}
catch(IOException ex) {
System.out.println("IO Exception");
}
}
}
MyServerThread.java
class MyServerThread extends Thread{
Socket sock;
public MyServerThread(Socket sock) {
this.sock = sock;
}
public void run() {
try {
PrintWriter pw = new PrintWriter(sock.getOutputStream());
Scanner cd = new Scanner(sock.getInputStream());
Scanner kb = new Scanner(System.in);
do {
String clientstr = cd.nextLine();
System.out.println("Client: "+clientstr);
if(clientstr.equalsIgnoreCase("quit")) {
break;
}
String str = kb.nextLine();
pw.println(str);
pw.flush();
}while(true);
sock.close();
pw.close();
}
catch(UnknownHostException ex) {
System.out.println("Unknown Host");
}
catch(IOException ex) {
System.out.println("IO Exception");
}
}
}
MyClient
class MyClient3 {
public static void main(String[] args) {
try {
InetAddress object = InetAddress.getByName("192.168.18.125");
Socket sock = new Socket(object, 4567);
PrintWriter pw = new PrintWriter(sock.getOutputStream());
Scanner cd = new Scanner(sock.getInputStream());
Scanner kb = new Scanner(System.in);
do {
String str = kb.nextLine();
pw.println(str);
pw.flush();
String strserver = cd.nextLine();
System.out.println("Server: "+strserver);
if(strserver.equalsIgnoreCase("quit")) {
break;
}
}while(true);
sock.close();
pw.close();
}
catch(UnknownHostException ex) {
System.out.println("Unknown Host");
}
catch(IOException ex) {
System.out.println("IO Exception");
}
}
}
當您編寫多線程客戶端服務器程序時,此代碼不正確。當多個客戶端連接到服務器時,必須分配一個ID,例如, 1,2,3,4等等。每個客戶端詳細信息請參閱這裏[link](http://mrbool.com/creating-a-multithreaded-chat-with-socket-in-java/34275) –