gpt4 book ai didi

java - 服务器客户端通信卡住`[命令提示符]

转载 作者:行者123 更新时间:2023-11-30 06:49:54 25 4
gpt4 key购买 nike

我是java网络编程的新手,所以请记住这一点。

我正在尝试开发一个多线程java服务器客户端应用程序。对于初学者,我的目标是仅在单个客户端和服务器之间开发一个通信 channel 。如果没有线程,单个客户端-服务器之间的通信可以正常工作。但是当我应用线程时,程序失败了。消息未发送。

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");
}
}
}

我的客户端

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");
}
}
}

最佳答案

最直接的问题是,在创建 MyServerThread 后,您没有在线程上调用 Thread#start()。但是,通常您不应该创建扩展线程的类。您应该创建一个 Runnable,并将其传递给 Thread#new(Runnable)。

关于java - 服务器客户端通信卡住`[命令提示符],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43029442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com