Server-Client chat program

半腔热情 提交于 2019-11-29 18:17:06

You need threads. The client in this examples read the lines from the System.in and sends the line to the server. The server sends an echo.

In your real application you have to take a look of the encoding

Server

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class HelloServer {

    public final static int defaultPort = 2345;

    public static void main(String[] args) {
        int port = defaultPort;
        try {
            port = Integer.parseInt(args[0]);
        } catch (Exception e) {
        }
        if (port <= 0 || port >= 65536) {
            port = defaultPort;
        }
        try {
            ServerSocket ss = new ServerSocket(port);

            while (true) {
                try {
                    Socket s = ss.accept();

                    new SocketThread(s).start();
                } catch (IOException e) {
                }
            }
        } catch (IOException e) {
            System.err.println(e);
        }
    }

    public static class SocketThread extends Thread {

        private Socket s;

        public SocketThread(Socket s) {
            this.s = s;
        }

        @Override
        public void run() {
            try {
                String response = "Hello " + s.getInetAddress() + " on port "
                        + s.getPort() + "\r\n";
                response += "This is " + s.getLocalAddress() + " on port "
                        + s.getLocalPort() + "\r\n";
                OutputStream out = s.getOutputStream();
                out.write(response.getBytes());
                BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
                while (true) {
                    String line = input.readLine();
                    System.out.println("IN: " + line);
                    s.getOutputStream().write(("ECHO " + line + "\n").getBytes());
                    s.getOutputStream().flush();
                    System.out.println(line);
                }
            } catch (IOException e) {
                System.err.println(e);
            }
        }

    }
}

Client

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketGetINetAdd {


    public static void main(String[] args) throws UnknownHostException, IOException {
        Socket socket = new Socket("localhost", 2345);
        InetAddress inetAddress = socket.getInetAddress();

        System.out.println("Connected to:: " + inetAddress.getHostName() + " Local address:: " + socket.getLocalAddress() + " Local Port:: " + socket.getLocalPort());
        new OutputThread(socket.getInputStream()).start();

        InputStreamReader consoleReader = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(consoleReader);
        while (true) {                        
            String inline = in.readLine();
            if (inline.equals("by")) {
                break;
            }
            inline += "\n";
            socket.getOutputStream().write(inline.getBytes());
            socket.getOutputStream().flush();
        }
    }

    public static class OutputThread extends Thread {

        private InputStream inputstream;

        public OutputThread(InputStream inputstream) {
            this.inputstream = inputstream;
        }

        @Override
        public void run() {
            BufferedReader input = new BufferedReader(new InputStreamReader(inputstream));
            while (true) {
                try {
                    String line = input.readLine();
                    System.out.println(line);
                } catch (IOException exception) {
                    exception.printStackTrace();
                    break;
                }
            }
        }

    }
}
Braj

Use server stream

OutputStream os = socket.getOutputStream();

instead of client console output stream

OutputStream os = System.out;

at client side to write back to server.


and at server side use client stream to read from client in the same manner.

InputStream in = s.getInputStream();

I have already posted a sample code on server-client communication. Read it for your learning.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!