下面我有我的服務器代碼在這裏:服務器不發送回一個確認信息給客戶
public void startServer() {
ServerSocket listener = selectUnusedPortFromRange(1024, 65535);
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
String command = null;
while (true) {
Socket socket = listener.accept();
System.out.println("Got a connection from: " + socket.getLocalPort());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
command = in.readLine();
System.out.println("GOT HERE"); //Not being printed out
if (command != null && !"".equals(command)) {
if ("connection".equals(command)) {
Writer writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.write("success\n");
writer.flush();
}
}
}
}
}
}
t.start();
}
這是我的客戶端:
public void makeConnection() {
try {
Socket socket = new Socket(IP, PORT);
Writer writer = new PrintWriter(socket.getOutputStream(), true);
writer.write("connection\n");
BufferedReader socketRead = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str;
while ((str = socketRead.readLine()) != null) {
if ("success".equals(str)) {
System.out.println("Successfully saved all hosts to: " + listOfHosts.get(i));
socketRead.close();
socket.close();
iStream.close();
writer.close();
}
}
}catch (Exception e) {
System.out.println(e.getMessage());
}
}
在客戶端後,我創造我插座連接到服務器我寫入「連接」到套接字的outputStream
,並等待服務器迴應確認成功。出於某種原因,連接不會發送到服務器。在服務器System.out.println("Got a connection from: " + socket.getLocalPort());
這一行沒有被打印出來。
有沒有什麼問題,我正在做。我無法發現它。當我嘗試連接到我的服務器時,我沒有收到異常。
進行仔細的檢查...你的客戶端是否使用服務器綁定的同一端口?我不知道'selectUnusedPortFromRange()'做了什麼,但我的猜測是它綁定到指定範圍內的一個隨機未使用的端口?確保你的客戶知道它綁定到哪個端口。 – SnakeDoc
@cricket是的,我剛剛注意到並改變了它。那是我的打字錯誤。我已經將其更改爲我的帖子中的正確代碼。 – CapturedTree
看過這個嗎? https://docs.oracle.com/javase/tutorial/networking/sockets/readingWriting.html –