简体   繁体   English

如何在与套接字服务器相同的计算机(IP)上运行套接字客户端?

[英]How to run a socket client on the same computer (IP) as a socket server?

I made a simple chat, it works as designed if to run a server on one IP, and client on another. 我进行了一个简单的聊天,如果在一个IP上运行服务器,而在另一个IP上运行客户端,则按设计工作。 This chat works with network. 此聊天适用于网络。 The problem is - when I try to run a server on my computer, the client on the my computer doesn't work. 问题是-当我尝试在计算机上运行服务器时,计算机上的客户端无法正常工作。 But if anybody else with another IP tries to connect to the server - everything is ok. 但是,如果有人使用另一个IP尝试连接到服务器-一切正常。 What can be the problem? 可能是什么问题?

Server: 服务器:

/**
 * Created by rnd on 7/4/2017.
 */

import java.io.*;
import java.net.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class VerySimpleChatServer {

    ArrayList clientOutputStreams;
    ArrayList<String> m_history;


    public static void main (String[] args) {
        new VerySimpleChatServer().go();
    }

    public void go() {
        clientOutputStreams = new ArrayList();
        m_history = new ArrayList<String>();
        try {
            ServerSocket serverSock = new ServerSocket(10001);

            while(true) {
                Socket clientSocket = serverSock.accept();

                Charset charset = StandardCharsets.UTF_8;
                OutputStreamWriter osw = new OutputStreamWriter( clientSocket.getOutputStream(), charset );
                PrintWriter writer = new PrintWriter( new BufferedWriter( osw ) );

//                PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());

                writer.println("Welcome to the chat 7 kids.... Семеро Козлят");
                writer.flush();

                clientOutputStreams.add(writer);
                Thread t = new Thread(new ClientHandler(clientSocket));
                t.start() ;
                System.out.println("got a connection");
            }
        } catch(Exception ex) {
            ex.printStackTrace();
        }
    } // Закрываем go


public class ClientHandler implements Runnable {

    BufferedReader reader;
    Socket sock;

    public ClientHandler(Socket clientSocket) {

        try {
            sock = clientSocket;
            InputStreamReader isReader = new InputStreamReader(sock.getInputStream(), StandardCharsets.UTF_8);
            reader = new BufferedReader(isReader);
        } catch(Exception ex) {ex.printStackTrace();}

    } // Закрываем конструктор

    public void run() {
        String message;

        tellHistory(m_history);

        try {

            while ((message = reader.readLine()) != null) {
                System.out.println("read " + message);
                m_history.add(message);

                tellEveryone(message);
            } // Закрываем while
        } catch(Exception ex) {ex.printStackTrace();}
    } // Закрываем run
} // Закрываем вложенный класс




    public void tellEveryone(String message) {
        Iterator it = clientOutputStreams.iterator();
        while(it.hasNext()) {
            try {
                PrintWriter writer = (PrintWriter) it.next();
                writer.println(message);
                writer.flush();
            } catch(Exception ex) {
                ex.printStackTrace();
            }
        } // Конец цикла while
    } // Закрываем tellEveryone

    public void tellHistory(ArrayList<String> history){


            try {
                PrintWriter writer1 = (PrintWriter) clientOutputStreams.get(clientOutputStreams.size() - 1);

                for (int i = 0; i < history.size(); i++) {
                    writer1.println(history.get(i));
                }
                //Идея в том, что бы вызывать историю только для последнего PrintWriter
                //может быть getsize поставить вместо i - writer1.println(history.get(history.size()));

                writer1.flush();
            } catch(Exception ex) {
                ex.printStackTrace();
            }


    }

} // Закрываем класс

Client: 客户:

/**
 * Created by rnd on 7/4/2017.
 */

import java.io.*;
import java.net.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class SimpleChatClient {

    JTextArea incoming;
    JTextField outgoing;
    JTextField name;
    BufferedReader reader;
    PrintWriter writer;
    Socket sock;
    String Myname;


    public static void main(String[] args) {
        SimpleChatClient client = new SimpleChatClient();
        client.go();}

    public void go(){
        JFrame frame = new JFrame("Ludicrously Simple Chat Client");
        JPanel mainPanel = new JPanel();
        incoming = new JTextArea(15,50);
        incoming.setLineWrap(true);
        incoming. setWrapStyleWord (true) ;
        incoming.setEditable(false);
        JScrollPane qScroller = new JScrollPane(incoming);
        qScroller. setVerticalScrollBarPolicy (ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS) ;
        qScroller. setHorizontalScrollBarPolicy (ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS) ;
        outgoing = new JTextField(20);
        name = new JTextField(5);
        JButton sendButton = new JButton("Send") ;
        JLabel label1 = new JLabel("name");

        sendButton.addActionListener(new SendButtonListener());
        mainPanel.add(qScroller);
        mainPanel.add(label1);
        mainPanel.add(name);
        mainPanel.add(outgoing);
        mainPanel.add(sendButton);

        setUpNetworking();

        Thread readerThread = new Thread(new IncomingReader());
        readerThread.start();

        frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
        frame.setSize(800,500);
        frame.setVisible(true);

    }

    private void setUpNetworking() {
        try {
            sock = new Socket("178.165.87.221", 10001);
//            sock = new Socket("127.0.0.1", 10001);
            InputStreamReader streamReader = new InputStreamReader(sock.getInputStream(), StandardCharsets.UTF_8 );
            reader = new BufferedReader(streamReader);


            Charset charset = StandardCharsets.UTF_8;
            OutputStreamWriter osw = new OutputStreamWriter( sock.getOutputStream(), charset );
            writer = new PrintWriter( new BufferedWriter( osw ) );

//            writer = new PrintWriter(sock.getOutputStream());
            System.out.println("networking established");
        } catch (IOException ex) {
                ex.printStackTrace();}
    }

    public class SendButtonListener implements ActionListener {
        public void actionPerformed (ActionEvent ev) {
            try {
                Myname = name.getText();
                writer.println(Myname + ": " + outgoing.getText());
                writer.flush();

            } catch(Exception ex) {
                ex.printStackTrace();
            }
            outgoing. setText ("") ;
                    outgoing.requestFocus () ;}
    }

    public class IncomingReader implements Runnable{
        @Override
        public void run() {
            String message;

            try{
                while((message=reader.readLine())!=null ){
                    System.out.println("read " + message);
                    incoming.append(message + "\n");
                }

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

}

is this 178.165.87.221 the local ip of the server machine? 178.165.87.221是服务器计算机的本地IP吗? local as if you run ipconfig or ifconfig in a terminal you will see this ip,,, if you want to run both server and client on same machine, the client should use the local IP of the server, 本地,就像在终端上运行ipconfigifconfig ,您将看到此ip。如果要在同一台计算机上同时运行服务器和客户端,则客户端应使用服务器的本地IP,

if you don't know the local IP, you can either use localhost or 127.0.0.1 如果您不知道本地IP,则可以使用localhost127.0.0.1

so client code should be one of those: 因此客户端代码应为以下代码之一:

sock = new Socket("127.0.0.1", 10001); //localhost alias

OR 要么

sock = new Socket("localhost", 10001); //localhost alias

OR 要么

sock = new Socket("192.168.100.10", 10001); // local IP [machine local IP might be something else, this is only an example]

Note: 178.165.87.221 looks like a real-ip, if you want to use this in client while on the same machine with the server, you may want to configure your router/network firewall/OS firewall to allow/forward the chat system port to the local-ip of the server machine 注意: 178.165.87.221看起来像一个真实IP,如果要在与服务器位于同一台计算机上的客户端中使用它,则可能需要配置路由器/网络防火墙/ OS防火墙允许/转发聊天系统端口到服务器计算机的本地IP

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

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