我正在编写一个在客户端和服务器之间使用TCP套接字连接的程序。当服务器启动时,我希望显示客户端需要用来连接的IP和端口,而当客户机连接时,我希望服务器显示客户机连接的是什么IP。我感到困惑的是,我应该使用哪一条命令来执行这些命令:
getInetAdress()
getLocalAdress()
getRemoteSocketAdress()
编辑
我之前使用了int port = 1234
和String IP = "localhost"
进行测试,而且测试成功了,但是我只在一台PC上使用它,所以我认为如果我在不同的计算机上启动服务器和客户机,localhost
就不能工作。
这是服务器端:
int port = 1234;
...
public void start() {
keepRunning = true;
// create socket
try {
ServerSocket server = new ServerSocket(port);
while (keepRunning) {
display("Waiting for client connections on "
+ server.getInetAddress().getLocalHost()
.getHostAddress() + ":" + port);
Socket conn = server.accept();
if (!keepRunning)
break;
ClientThread t = new ClientThread(conn);
cList.add(t);
t.start();
这是客户:
int port = 1234;
String IP = "localhost";
//these variables can be changed from Client GUI before making connection
...
public boolean start() {
try {
socket = new Socket(IP, port);
} catch (Exception e) {
display("Error connectiong to server:" + e);
return false;
}
try {
sInput = new ObjectInputStream(socket.getInputStream());
sOutput = new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
display("Exception creating new Input/output Streams: " + e);
return false;
}
当我启动服务器时,
display("Waiting for client connections on " + server.getInetAddress().getLocalHost().getHostAddress() + ":" + port);
返回这个:
Waiting for client connections on 192.168.1.104:1234
这是我想要的,但我还是拿不到它给我看港口。1234
是我使用的一个固定值,但是我想使用ServerSocket server = new ServerSocket(0);
动态地指定端口,然后当我启动客户机时,我只输入从服务器和连接中获得的值。
我试图在服务器的server.getLocalPort()
行中使用display
,它返回了55410或类似的东西,但是当我把这个端口放在客户端以建立连接时,它就不起作用了。我从客户那里得到Error connectiong to server:java.net.ConnectException: Connection refused: connect.
发布于 2014-05-11 12:48:12
要获取ServerSocket正在侦听的当前端口,请使用getLocalPort();
http://download.java.net/jdk7/archive/b123/docs/api/java/net/ServerSocket.html#getLocalPort%28%29
getLocalPort
public int getLocalPort()
Returns the port number on which this socket is listening.
If the socket was bound prior to being closed, then this method will continue to return the port number after the socket is closed.
编辑:刚刚看到你的编辑。您是否试图通过显式引用IP和端口来连接?如果是这样,而且仍然失败,您的服务器机器可能正在运行防火墙。我会先查一下的。
https://stackoverflow.com/questions/23592238
复制相似问题