我有一个套接字编程代码。
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
代码有什么问题??我尝试过增加和减少超时值,但是它给出了相同的输出。
代码有什么问题?
您的代码没有错。您设置了50秒的接受超时,接受了50秒钟的阻止而没有客户端尝试连接,因此SocketTimeoutException
抛出了一个错误。这里的一切都按设计工作。
当然有可能:
所有这些都是取决于您的要求的设计决策。
您也有可能在客户端中输入了错误的主机名,但是由于您忽略了客户端中的异常:
catch(IOException e)
{
}
您将永远无法找到答案。永远不要忽视IOExceptions
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句