我有一个套接字编程代码..
Server Program
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread
{
private static int port;
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(50000);
}
public void run()
{
while(true)
{
try
{
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to "
+ server.getRemoteSocketAddress());
DataInputStream in =
new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out =
new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to "
+ server.getLocalSocketAddress() + "\nGoodbye!");
server.close();
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String [] args)
{
port=9000;
try
{
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
客户端代码是......
import java.io.*;
import java.net.*;
public class GreetingClient
{
private static String serverName;
public static void main(String [] args)
{
String sName = "MyServerName";
int port = 9000;
try
{
System.out.println("Connecting to " + sName
+ " on port " + port);
Socket client = new Socket(sName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out =
new DataOutputStream(outToServer);
out.writeUTF("Hello from "
+ client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
}catch(IOException e)
{
}
}
}
代码编译得很好。但是当我运行程序时,首先是服务器,然后是客户端,服务器显示
Waiting for client on port 9000...
Socket timed out!
,客户端显示
Connecting to MyServerName on port 9000
代码有什么问题?我已经尝试增加和减少超时值,但它提供相同的输出。
答案 0 :(得分:5)
代码有什么问题?
您的代码没有任何问题。您设置了50秒的接受超时,在没有客户端尝试连接的情况下接受阻止50秒,因此抛出了SocketTimeoutException
。这里的一切都按设计工作。
当然有可能:
所有这些都是取决于您的要求的设计决定。
您也可能在客户端中输入了错误的主机名,但是因为您忽略了客户端中的异常:
catch(IOException e)
{
}
你无法找到答案。永远不要忽略IOExceptions
。
答案 1 :(得分:0)
上面的代码完全使用客户端中的sName作为“localhost”,因为我在本地运行客户端和服务器:
String sName = "localhost";
如果您希望客户端连接到服务器,请验证您的服务器名称。