服务器-客户端聊天程序 [英] Server-Client chat program

查看:112
本文介绍了服务器-客户端聊天程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个服务器-客户端聊天程序.

I am writing a server-client chat program.

这是我的代码

服务器:

import java.io.IOException;
import java.io.InputStream;
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();

                    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());
                    System.out.write(response.getBytes());
                    InputStream in = s.getInputStream();

                    System.out.println("from client");
                    int z = 0;
                    while ((z = in.read()) != -1) {
                        System.out.write(z);
                    }

                } catch (IOException e) {
                }
            }
        } catch (IOException e) {
            System.err.println(e);
        }
    }
}

客户:

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
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("192.xxx.x.xxx", 2345);
        InetAddress inetAddress = socket.getInetAddress();

        System.out.println("Connected to:: " + inetAddress.getHostName() + " Local address:: "
                + socket.getLocalAddress() + " Local Port:: " + socket.getLocalPort());
        BufferedInputStream bfINPUT = new BufferedInputStream(socket.getInputStream());
        int b = 0;
        OutputStream os = System.out;
        while ((b = bfINPUT.read()) != -1) {
            os.write(b);
        }
        OutputStream osNew = socket.getOutputStream();
        String s = "This Is The Client"; // data to be sent
        osNew.write(s.getBytes());
        os.write(s.getBytes());

}

我已经通过程序将它们连接起来.

I've connected them through my program.

但是现在我想知道如何从客户端将一些数据发送回服务器?

用于客户端(用于向服务器发送数据)的代码是什么,以及用于在控制台(服务器)上显示从客户端接收到的数据的服务器的代码是什么?

What would be the code for client(for sending data to server) and also the code for the server for showing the data received from the client on the console(server)?

P.S-我是网络编程的新手.请不要批评我的编码风格:P

P.S- I am a novice in network programming. Please do not criticize my coding style :P

推荐答案

您需要线程.在此示例中,客户端从System.in中读取行,并将该行发送到服务器.服务器发送回显.

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

服务器

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

    }
}

客户

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;
                }
            }
        }

    }
}

这篇关于服务器-客户端聊天程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆