我正在嘗試學習Java網絡編程,但我遇到了一些障礙。我已經寫了一個服務器和一個客戶端,但每次嘗試連接它們時,我都會立即發現連接關閉錯誤。然後,我試圖編輯它,但現在我得到一個連接拒絕錯誤。放棄這一點,我決定在一個非常簡單的服務器上測試Sockets和ServerSocket的基礎知識。這樣做,我想出了這兩個類:Java SocketServer正在接受來自Socket客戶端的輸入,但Socket客戶端沒有從SocketServer接收輸入
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;
public class SimpleServer {
public static void main(String[] args) throws Exception {
System.out.println("hey there");
ServerSocket server = new ServerSocket(50010);
Socket socket = server.accept();
System.out.println("Connection at " + socket);
InputStream in = socket.getInputStream();
int c = 0;
while ((c = in.read()) != -1) {
System.out.print((char)c);
}
OutputStream out = socket.getOutputStream();
for (byte b : (new String("Thanks for connecting!")).getBytes()) {
out.write(b);
out.flush();
}
in.close();
out.close();
socket.close();
server.close();
}
}
和
import java.net.Socket;
import java.io.*;
public class SimpleClient {
public static void main(String[] args) throws Exception {
System.out.println("Attempting connection");
Socket s = new Socket("130.49.89.208", 50010);
System.out.println("Cool");
OutputStream out = s.getOutputStream();
for (byte b : (new String("Hey server\r\nThis message is from the client\r\nEnd of message\r\n")).getBytes()) {
out.write(b);
out.flush();
}
InputStream in = s.getInputStream();
int c = 0;
System.out.println("this message will print");
while ((c = in.read()) != -1) {
System.out.print((char)c);
System.out.println("this does not print");
}
out.close();
in.close();
s.close();
}
}
服務器收到客戶端的消息完全正常,但是當它是服務器的轉寫到客戶端,一切都會阻止。
服務器的輸出:
-java SimpleServer
----hey there
----Connection at Socket[addr=/130.49.89.208,port=59136,localport=50010]
----Hey server
----This message is from the client
----End of message
客戶的輸出:
-java SimpleClient
----Attempting connection
----Cool
----this message will print
客戶端和服務器上我的以太網連接到一所大學的互聯網連接在筆記本電腦上運行,有沒有什麼幫助。