我试图使用套接字连接服务器,但是当我将参数设置为 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();
}
}