Sergei Kan
Sergei Kan

Reputation: 93

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. 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. 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();
            }
        }
    }

}

Upvotes: 0

Views: 2555

Answers (1)

Yazan
Yazan

Reputation: 6082

is this 178.165.87.221 the local ip of the server machine? 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,

if you don't know the local IP, you can either use localhost or 127.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

Upvotes: 4

Related Questions