【发布时间】:2013-04-23 06:29:41
【问题描述】:
所以我正在尝试绑定并监听我学校服务器上的一个端口,以便在我的网络课程中分配作业。我遇到的问题是,当我在 java 中创建 ServerSocket 时,我经常收到 IOException,即使我尝试绑定到位于较高频段的端口也是如此。
我最初尝试绑定到端口 1088(或多或少是出于寄予厚望),但如果不成功,我将尝试绑定到 1024 以上的随机端口(服务器上保留任何更低的端口)。
这是我得到的:
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.UnknownHostException;
import java.util.Random;
public class main
{
/**
* @param args
*/
public static void main(String[] args)
{
Random r = new Random();
boolean connected = true;
ServerSocket serverSocket = null;
int welcomePortNum = new Integer(args[0]);
if(welcomePortNum >= 65536)
{
System.out.println("Invalid welcome port number, terminating execution.");
System.exit(0);
}
do
{
connected = true;
System.out.println(welcomePortNum);
try
{
serverSocket = new ServerSocket(welcomePortNum, 5, InetAddress.getByName("loki.ist.unomaha.edu"));
} catch(UnknownHostException e)
{
System.err.println("Could not connect to 'loki.ist.unomaha.edu'.");
connected = false;
//System.exit(1);
}catch(IOException e)
{
System.err.println("Could not get the I/O for the connection to loki.ist.unomaha.edu.");
connected = false;
//System.exit(1);
}
if(connected == false)
welcomePortNum = r.nextInt(64512) + 1024;
System.out.println(connected);
}
while(connected == false);
// TODO Auto-generated method stub
}
}
有什么想法吗?
【问题讨论】:
-
不要使用
ServerSocket,而应该使用Socket(带有远程服务器的主机和端口)连接到远程服务器,并从中读取数据。
标签: java serversocket