所以我的服务器看起来像这样
import java.net.*;
import java.io.*;
public class Server extends Thread {
private ServerSocket serverSocket;
public Server(int port) throws IOException {
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(20000);
}
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) {
int port = 5000;
try {
Thread t = new Server(port);
t.start();
}catch(IOException e) {
e.printStackTrace();
}
}
}
当我运行它时,一切都很顺利。我的客户端也是这样的。
import java.net.*;
import java.io.*;
public class Client {
public static void main(String [] args) {
String serverName = "Server";
int port = 5000;
try {
System.out.println("Connecting to " + serverName + " on port " + port);
Socket client = new Socket(serverName, 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) {
System.out.println("Error!");
}
}
}
运行我的客户端后,我在控制台中得到了它。
Connecting to Server on port 5000
java.net.UnknownHostException: Server
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)
at maple.Client.main(Client.java:16)
第16行看起来像这样
Socket client = new Socket(serverName, port);
修改
当我运行代码时更改为有效的服务器地址后,我只获得某些语句运行,然后它只是超时。这是为什么?
Waiting for client on port 5000...
Just connected to /127.0.0.1:57355
Hello from /127.0.0.1:57355
Waiting for client on port 5000...
Socket timed out!
答案 0 :(得分:1)
服务器名称分配给字符串文字"Server"
,而不是有效的主机地址。
答案 1 :(得分:1)
它超时,因为在构造函数中你设置了20秒的生存时间。
serverSocket.setSoTimeout(20000);
删除它,你应该没事。