我正在尝试创建与网络服务器的套接字连接。
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Connection{
public final static int PORT = 1337;
public Connection(){
ServerSocket svrSocket = null;
try{
svrSocket = new ServerSocket(PORT);
System.out.println("Conected to: " + PORT);
Socket con = null;
while(true)
{
try{
con = svrSocket.accept();//on this part the program stops
System.out.println("Client request accepted");
PrintWriter out = new PrintWriter(con.getOutputStream());
out.flush();
}catch(IOException ex)
{
ex.printStackTrace();
}
}
}catch(IOException ex)
{
System.err.println(ex);
System.out.println("Unable to attach to port");
}
}
}
客户端请求con = svrSocket.accept();
未运行。我这样说是因为该行之后的消息不会显示。
为什么它不接受客户端请求?是否可以使用 Web 浏览器测试服务器?请原谅我糟糕的编程风格。
谢谢。
最佳答案
您需要有一个客户端连接到您的服务器,以便您的服务器能够接受连接,直到发生这种情况为止,代码将在那一行等待。
如果您运行代码的一个实例,然后编译并运行此代码(同时您的代码也在运行),您会发现您收到客户端请求已接受消息,如果由于端口而收到 IOException,请更改将它们中的端口设置为在 cmd 中调用 netstat -o
时不会出现的内容。
import java.io.*;
import java.net.*;
public class TestCon
{
public static void main(String[] args)
{
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket("127.0.0.1", 1337);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
out.println("Hello Server!");
System.out.println(in.readLine());
out.close();
in.close();
echoSocket.close();
} catch (UnknownHostException e) {
System.err.println("Host Unknown");System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection.");System.exit(1);
}
}
}
关于java - 使用服务器 Socket 接受客户端请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17909426/