public class Main {
private static Socket socket;
public static void main(String[] args) {
try {
int port = 13579;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Servidor Iniciado escuchando al puerto " + port);
while (true) {
socket = serverSocket.accept();
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
String request = dataInputStream.readUTF();
String returnMessage = "";
if (request.startsWith("ISO0060000500800")) {
returnMessage = "ISO006000050081082200000020000000400000000000000" + request.substring(48, 64) + "00" + request.substring(64);
} else {
System.out.println("Received: " + request);
try {
InterpretePostilionEvertec interpretePostilionEvertec = new InterpretePostilionEvertec();
Transaccion transaccion = interpretePostilionEvertec.interpretarRequest(request);
GestorTransacciones gestorTransacciones = new GestorTransacciones();
try {
returnMessage = interpretePostilionEvertec.interpretarResponse(gestorTransacciones.abono(transaccion), request);
} catch (Exception e) {
}
} catch (Exception e) {
returnMessage = "Error: " + e.getMessage();
}
}
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF(returnMessage);
dataOutputStream.flush();
System.out.println("Return: " + returnMessage);
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
我从客户端A收到的第一条消息是好的,但是当他试图再向我发送一封消息时,从未被接受。卡在socket = serverSocket.accept(); 我做错了什么?请帮帮我:D
**我需要保持会话。我收到的第一个字符串就像是echo或anotlage,第二个是实际的请求。
答案 0 :(得分:2)
您的代码每个接受的连接只读取一个请求。你需要一个内部循环,或者更好的是在循环中启动一个单独的线程来处理每个接受的连接。
答案 1 :(得分:0)
尝试这样的事情
/**
* Continuously listen on port 8888. accept() will block
* until a new connection is requested. When a new connection
* is received, spawn a new thread to service it,
* then listen for more.
*/
public static void main(String[] args) throws Exception {
ServerSocket listener = new ServerSocket(8888);
ExecutorService es = Executors.newCachedThreadPool();
try {
while (true) {
es.submit(new SomeObject(listener.accept()));
}
} finally {
listener.close();
es.shutdownNow();
}
}
SomeObject实现Runnable
答案 2 :(得分:-1)
我认为您应该只接受来自同一客户的连接一次。您已经根据需要从中读取了套接字。当你从另一个客户端获得新连接时使用accept。