java - 使用服务器 Socket 接受客户端请求

标签 java sockets socketserver

我正在尝试创建与网络服务器的套接字连接。

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/

相关文章:

python - 杀死在不同端口上运行的多个httpserver

ios - 你能使用 Swift ARC 快速释放稀缺资源(文件描述符、网络套接字)吗?

Java:通过套接字发送后公钥不同

Java EE - 更改 index.jsp 的目录

java - GSON - 具有命名策略的可选和必填字段

java - 在 readLine() 之后使用 readLong() 进行套接字通信

python - SocketServer 在退出时不释放端口

python - 通过自定义处理程序关闭 python TCPServer

java - 将结果更新到 Android 的 AlertDialog 的 TextView

java - 卡在 XPath 上