简体   繁体   English

使用ServerSocket而没有端口转发?

[英]Using a ServerSocket without port forwarding?

This may be a stupid question, but here goes. 这可能是一个愚蠢的问题,但这是正确的。 Im writing this chat program, where there is a server, and clients that can connect to it. 我正在编写此聊天程序,其中有一个服务器以及可以连接到它的客户端。 I want to implement private messaging into the program, but I don't know how to get the clients to directly connect to eachother. 我想在程序中实现私人消息传递,但是我不知道如何使客户端直接相互连接。 For the server, I used a ServerSocket, which runs on a single port. 对于服务器,我使用了在单个端口上运行的ServerSocket。 To get that to work, I needed to forward a port to the server. 为了使它正常工作,我需要将端口转发到服务器。 Is there a way to get the clients to wait for connections, without forwarding a port to them? 有没有一种方法可以让客户端等待连接而无需向其转发端口?

Thanks 谢谢

The whole point of TCP/IP is that a single client connects to a predefined port on a server. TCP / IP的全部要点是,单个客户端连接到服务器上的预定义端口。 So yes, you'll also need to have a ServerSocket on the client that's going to accept the direct connection. 因此,是的,您还需要在客户端上具有一个ServerSocket ,它将接受直接连接。 You'll almost always run into trouble with port forwarding and the like, which is why UPnP was invented one day. 几乎总是会遇到端口转发之类的麻烦,这就是UPnP发明的一天。

What you are trying to do is 'peer to peer' connectivity, aka P2P, which is always, by its very definition, plagued by firewalling problems. 您正在尝试做的是“点对点”连接(也称为P2P),按照其定义,它始终受到防火墙问题的困扰。 As such it's usually, especially for a chat, easier to use the central server as 'switchboard' server and relay the private messages as well. 因此,通常,特别是对于聊天,更容易将中央服务器用作“总机”服务器并中继私人消息。

I've written not long time ago a template for multiple client - server application, that might help you to solve your problem. 不久前,我已经为multiple client - server应用程序编写了模板,这可能会帮助您解决问题。 The rest of your question was already answerd by @Niels, I think ;) 我想您的其余问题已经由@Niels回答了;)

import java.net.*;
import java.io.*;

class ServeConnection extends Thread {
        private Socket socket = null;
        private BufferedReader in = null;
        private PrintWriter out = null;

        public ServeConnection(Socket s) throws IOException {

                // init connection with client
                socket = s;
                try {
                        in = new BufferedReader(new InputStreamReader(
                                        this.socket.getInputStream()));
                        out = new PrintWriter(this.socket.getOutputStream(), true);
                } catch (IOException e) {
                        System.err.println("Couldn't get I/O.");
                        System.exit(1);
                }                
                start();
        }

        public void run() {

                System.out.println("client accepted from: " + socket.getInetAddress()
                                + ":" + socket.getPort());

           // get commands from client, until is he communicating or until no error
           // occurs
                String inputLine, outputLine;

                try {
                        while ((inputLine = in.readLine()) != null) {


                                System.out.println("request: " + inputLine);
                                outputLine = inputLine;    
                                out.println("I've recived "+outputLine);                                 
                } catch (IOException e) {
                        e.printStackTrace();
                }

                System.out.println("server ending");
                out.close();
                try {
                        in.close();
                        socket.close();
                } catch (IOException e) {
                        e.printStackTrace();
                }
        }
}

class Server {
        public static void svr_main(int port) throws IOException {
                ServerSocket serverSocket = null;
                try {
                        serverSocket = new ServerSocket(port);
                } catch (IOException e) {
                        System.err.println("Could not listen on port: " + port);
                        System.exit(1);
                }

                System.out.println("Server ready");

                try {
                        while (true) {
                                Socket socket = serverSocket.accept();
                                try {
                                        new ServeConnection(socket);
                                } catch (IOException e) {
                                        System.err.println("IO Exception");
                                }
                        }
                } finally {
                        serverSocket.close();
                }
        }
}

class Client {      
        static Socket echoSocket = null;
        static PrintWriter out = null;
        static BufferedReader in = null;





        public static void cli_main(int port, String servername) throws
IOException {
                try {
                        echoSocket = new Socket(servername, port);
                        out = new PrintWriter(echoSocket.getOutputStream(), true);
                        in = new BufferedReader(new InputStreamReader(
                                        echoSocket.getInputStream()));
                } catch (UnknownHostException e) {
                        System.err.println("Don't know about host: " + servername);
                        System.exit(1);
                } catch (IOException e) {
                        System.err.println("Couldn't get I/O for " + servername);
                        System.exit(1);
                }

                System.out.println("Client ready!");
                while (true) {

                        inputLine = (in.readLine().toString());
                        if (inputLine == null) {
                                System.out.println("Client closing!");
                                break;
                        }

                        // get the input and tokenize it
                        String[] tokens = inputLine.split(" ");


                }

                out.close();
                in.close();
                echoSocket.close();
                System.out.println("Client closing");
        }
}

public class MyClientServerSnippet{
        public static void main(String[] args) throws IOException {
                if (args.length == 0) {
                        System.err.println("Client: java snippet.MyClientServerSnippet<hostname> <port>");
                        System.err.println("Server: java snippet.MyClientServerSnippet<port>");
                         System.exit(1);
                }
                else if (args.length > 1) {                   
                        System.out.println("Starting client...\n");
                        Client client = new Client();
                        client.cli_main(3049, "127.0.0.1");
                } else {
                        System.out.println("Starting server...\n");
                        Server server = new Server();
                        server.svr_main(3049);
                }
        }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM