服务器到套接字的通信

时间:2018-06-27 10:22:21

标签: java sockets tcp

关于使用localhost以外的主机时,我对Java中的SocketServer和Socket连接有疑问。

我正在尝试编写一个简单的聊天程序,希望与我家中的其他人建立联系。这是我创建服务器套接字和套接字的代码:

private static boolean clientIsConnected = false;

public static void main(String[] args) {


    new Thread(new Runnable(){
        public void run(){
            Server server = null;
            try{
                server = new Server();
                clientIsConnected = server.getClient().isConnected();
                while(clientIsConnected){
                    System.out.println("Message From Client: ");
                    System.out.print(server.recieveMessage());
                    System.out.println();
                }

            }catch(IOException e){
                e.printStackTrace();
            }

            finally{

                try{
                    if(server!=null)server.getServer().close();
                    if(server!=null)server.getClient().close();
                }catch(IOException e){
                e.printStackTrace();
                }
            }
        }
    }).start();




    new Thread(new Runnable(){
        public void run(){
            Client client = null;
            try{
                Thread.sleep(2000);
                client = new Client();
                clientIsConnected = client.getClient().isConnected();

                System.out.println("Exit with \'!\'");
                while(clientIsConnected){

                    Scanner userInput = new Scanner(System.in);
                    String message = userInput.next();

                    clientIsConnected = message.equals("!");
                    client.sendMessage(message);
                }

            } catch(InterruptedException i){
                i.printStackTrace();
            }
            catch(IOException e){
                e.printStackTrace();
            }

            finally{

                try{
                    if(client!=null)client.getClient().close();
                }catch(IOException e){
                e.printStackTrace();
                }
            }
        }
    }).start();
}

static class Server{

    protected static final int PORT = 50211;
    private final ServerSocket server;
    protected Socket client;


    Server() throws IOException{
        server = new ServerSocket(PORT);
        client = server.accept();
    }

    public boolean sendMessage(String message) throws IOException{
      if(message == null)return false;
      if(message.isEmpty())return false;

      client.getOutputStream().write(message.getBytes());
      return true;
    }

    public String recieveMessage() throws IOException{
    StringBuilder message = new StringBuilder();

    int character;
    while((character = client.getInputStream().read())!= -1)
        message.append((char)character);

    return message.toString();
    }

    public ServerSocket getServer() {
        return server;
    }

    public Socket getClient() {
        return client;
    }
}

static class Client extends Server{
    Client() throws IOException{
     client = new Socket("localhost",PORT);
    }
}

ServerRelay(运行): 运行:

java.net.BindException: Address already in use: JVM_Bind
at java.net.DualStackPlainSocketImpl.bind0(Native Method)
at java.net.DualStackPlainSocketImpl.socketBind(DualStackPlainSocketImpl.java:106)
at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:387)
at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:190)
at java.net.ServerSocket.bind(ServerSocket.java:375)
at java.net.ServerSocket.<init>(ServerSocket.java:237)
at java.net.ServerSocket.<init>(ServerSocket.java:128)
at socketrelay.SocketRelay$Server.<init>(SocketRelay.java:100)
at socketrelay.SocketRelay$1.run(SocketRelay.java:28)
at java.lang.Thread.run(Thread.java:748)
java.net.BindException: Address already in use: JVM_Bind
at java.net.DualStackPlainSocketImpl.bind0(Native Method)
at java.net.DualStackPlainSocketImpl.socketBind(DualStackPlainSocketImpl.java:106)
at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:387)
at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:190)
at java.net.ServerSocket.bind(ServerSocket.java:375)
at java.net.ServerSocket.<init>(ServerSocket.java:237)
at java.net.ServerSocket.<init>(ServerSocket.java:128)
at socketrelay.SocketRelay$Server.<init>(SocketRelay.java:100)
at socketrelay.SocketRelay$Client.<init>(SocketRelay.java:132)
at socketrelay.SocketRelay$2.run(SocketRelay.java:60)
at java.lang.Thread.run(Thread.java:748)

成功完成(总时间:2秒)

//解决了此问题

static class Client extends Server{
    private Socket client;
    Client() throws IOException{
     client = new Socket("localhost",PORT);
    }

    @Override
    public Socket getClient() {
        return client; 
    }

    @Override
    public boolean sendMessage(String message) throws IOException{
      if(message == null)return false;

      client.getOutputStream().write(message.getBytes());
      return true;
    }

    @Override
    void close() {
        try
        {
            if(client!=null)client.close();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}
static class Server{

    protected static final int PORT = 65535 - new Random().nextInt(300);
    ServerSocket server;
    Socket serverClient;


    public boolean sendMessage(String message) throws IOException{
      if(message == null)return false;

      serverClient.getOutputStream().write(message.getBytes());
      return true;
    }

    public String recieveMessage() throws IOException{
    StringBuilder message = new StringBuilder();

    int character;
    while((character = serverClient.getInputStream().read())!= -1)
        message.append((char)character);

    return message.toString();
    }

    public ServerSocket getServer() {
        return server;
    }

    public void setServer(ServerSocket server) {
        this.server = server;
    }



    public Socket getClient() {
        return serverClient;
    }

    private void setClient(Socket socket) {
       serverClient = socket; //To change body of generated methods, choose Tools | Templates.
    }

    void close()
    {
        try
        {
            if(server!=null)server.close();
            if(serverClient!=null)serverClient.close();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}
private static volatile boolean didUserExit = false;

public static void main(String[] args) {
        startServer();
        startClient();
}

static void startClient(){
    new Thread(new Runnable(){
        public void run(){

            Client client = null;
            try{
                client = new Client();
                didUserExit = false;

                System.out.println("Exit with \'!\'");
                while(!didUserExit){

                    System.out.println("Send a message to server: ");
                    Scanner userInput = new Scanner(System.in);
                    String message = userInput.next();

                    didUserExit = message.equals("!");
                    if(!didUserExit)client.sendMessage(message);
                }

            }
            catch(IOException e){
                e.printStackTrace();
            }

            finally{
               if(client!=null)client.close();
            }

        }
    }).start();
}

static void startServer(){
new Thread(new Runnable(){
        public void run(){

            Server server = null;
            try{
                server = new Server();
                while(!didUserExit){

                    if(server.getServer()== null){
                    server.setServer(new ServerSocket(server.PORT));
                    server.setClient(server.getServer().accept());
                    }

                    String clientMessage = server.recieveMessage();

                    if(!clientMessage.isEmpty()){
                        System.out.println("Message From Client: ");
                        System.out.print(clientMessage);
                        System.out.println();
                    }

              }

            }catch(IOException e){
                e.printStackTrace();
            }

            finally{
              if(server!=null)server.close();
            }

        }
    }).start();
}

现在的问题是这样的: run: Exit with '!' Send a message to server: Hello world Send a message to server: ! Message From Client: Hello BUILD SUCCESSFUL (total time: 8 seconds)

请注意发送到服务器的消息如何不包含它必须是的“世界”(“ Hello world”);第一个空格字符之后的所有内容都将不包括在内。

可能是什么原因引起的...我试图弄清楚这一点,但没有成功。

0 个答案:

没有答案