我試圖使用套接字來連接服務器,但是當我把參數設置爲localhost時,它的工作原理。但是當我把我的IP地址在那裏它永遠不會奏效,所以我不知道什麼是錯的,我得到的IP地址是從http://whatismyipaddress.com插座從來沒有連接
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
public static void main(String [] arg) throws Exception
{
Socket socket;
BufferedReader stdIn;
BufferedReader fromServer;
PrintWriter toServer;
String s;
String result;
socket = new Socket("96.63.208.240", 5000);
stdIn = new BufferedReader(new InputStreamReader(System.in));
fromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
toServer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
while ((s = stdIn.readLine()) != null)
{
toServer.println(s);
result = fromServer.readLine();
System.out.println("reverse: " + result);
}
socket.close();
}
}
的服務器側
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String [] arg) throws Exception
{
ServerSocket serverSocket = new ServerSocket(5000, 10);
Socket socket;
serverSocket.setReuseAddress(true);
while ((socket = serverSocket.accept()) != null)
{
System.out.println("Accepted an incoming connection");
new SessionThread(socket).start();
}
serverSocket.close();
}
}
假設這是在家庭型網絡上 - 是否啓用了端口5000上的端口轉發? – Steve101
對不起,你知道該怎麼做? –
如果您登錄到路由器,應該有一個端口轉發部分,並將來自端口5000的通信路由到本地IP。 – Steve101