0
我在Netbeans中有一个简单的客户端 - 服务器应用程序,它向服务器发送登录请求并侦听来自服务器的答案。无法用Java中的Serversocket多次发送请求
我在客户端的构造函数声明这些代码:
try {
socket = new Socket("localhost", 12345);
oos = new ObjectOutputStream(socket.getOutputStream());
ois = new ObjectInputStream(socket.getInputStream());
}catch (Exception e) {
e.printStackTrace();
}
和请求发送时,点击与str
按钮是登录的信息:
public void request_login(String str) {
try {
this.oos.writeInt(1);
this.oos.writeUTF(str);
this.oos.flush();
System.out.println("CLIENT: Sent!");
int responseCode = this.ois.readInt();
if (responseCode == Protocol.OK) {
//OK handler
}else {
//Fail handler
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NullPointerException ee) {
ee.printStackTrace();
}
}
这是我的服务器:
public ServerATM() {
try {
this.serversocket = new ServerSocket(12345);
System.out.println("Server is listening!");
for(;;){
Socket socket = this.serversocket.accept();
Thread t = new ClientThread(socket);
t.start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and the ClientThread
class:
public ClientThread(Socket socket) {
this.socket = socket;
try {
this.ois = new ObjectInputStream(socket.getInputStream());
this.oos = new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void processThread() {
try {
int requestCode = this.ois.readInt();
switch(requestCode) {
case 1:
String request = ois.ReadUTF();
// Handle the code with the request.
//Then return the result for client
oos.writeInt(5);
oos.flush();
break;
case 2:
break;
}
} catch (IOException ex) {
Logger.getLogger(ClientThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void run(){
processThread();
}
该代码适用于第一次点击。但是,当我更改输入字符串,然后再次单击该代码只是挂起。 processThread
只在第一次点击时调用一次,第二次点击不会调用它,因此它不会执行我的代码。
看起来像发送请求时,它在服务器中创建一个新的线程,但在这种情况下,它已经创建,因此它不会再运行。无论如何,我可以多次发送请求,服务器将全部收听它们?
谢谢
谢谢你,它的工作原理! –