所有我已閱讀並觀看關於Java Socket編程涉及一個共同的,必要的話,這是本地主機教程。我一直在玩Java服務器客戶端programms的一會兒,做實驗的一點點。但每次,我的電腦是在服務器和客戶端,所以我也不太明白如何使當談到嘗試連接到託管我的計算機上的服務器以外的其他計算機上工作的事情。爪哇 - socket編程
採取以下基本服務器 - 客戶端類,例如:
服務器級
public class TestServerSocket {
public static void main(String args[]) throws IOException {
final int portNumber = 444;
System.out.println("Creating server socket on port " + portNumber);
ServerSocket serverSocket = new ServerSocket(portNumber);
while (true) {
Socket socket = serverSocket.accept();
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//...code...
}
socket.close();
pw.close();
os.close();
br.close();
}
}
客戶端級
public class TestClientSocket {
public static void main(String args[]) throws IOException {
final String host = "localhost";
final int portNumber = 444;
System.out.println("Creating socket to '" + host + "' on port " + portNumber);
while (true) {
Socket socket = new Socket(host, portNumber);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader userInputBR = new BufferedReader(new InputStreamReader(System.in));
//...code...
}
socket.close();
out.close();
br.close();
userInputBR.close();
}
}
現在,說我要上運行TestServerSocket我的電腦,並讓我的朋友在他的上面運行TestClientSocket。這些代碼需要做些什麼改變才能實現?
https://superuser.com/questions/321734/how-does-localhost-127-0-0-1-work should give something to read –