【问题标题】:Server-Client chat program服务器-客户端聊天程序
【发布时间】:2014-05-17 20:31:06
【问题描述】:

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

这是我的代码

服务器:

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

}

我已通过我的程序将它们连接起来。

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

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

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

【问题讨论】:

  • 您希望我们为您编写代码吗?你试过什么?什么不工作?
  • 这是一个非常广泛的问题。 SO 可以帮助您解决您面临的特定问题。如果您想学习网络编程,请坚持使用网络上的大量教程之一。例如:OracleJavaWorld 仅举两个。
  • @enterbios=不要因为疯狂的原因投票否决问题。我已经提到我无法编写从客户端向服务器发送数据的代码。我想学习代码,因为在其他地方找不到。

标签: java sockets networking network-programming serversocket


【解决方案1】:

使用服务器流

OutputStream os = socket.getOutputStream();

而不是客户端控制台输出流

OutputStream os = System.out;

在客户端写回服务器。


在服务器端使用客户端流以相同的方式从客户端读取。

InputStream in = s.getInputStream();

我已经在server-client communication 上发布了示例代码。阅读它以供您学习。

【讨论】:

  • 接下来呢?你有什么问题吗?为了更好地理解,我在帖子中提到了一些链接。请看一看。
  • 我已经发布了很多关于客户端-服务器通信的示例。请先阅读。你会找到你的解决方案。
  • 我已经编辑了我的程序。我已经使用了您要求我使用的一些技术。但是在服务器控制台上仍然没有输出客户端发送的数据。 :(请帮帮我。
  • @brij 我已经重写了程序并附加了您要求我添加的代码。但是他的服务器控制台上没有输出。
  • 让我检查一下。我会回来的。
【解决方案2】:

你需要线程。此示例中的客户端从System.in 读取行并将该行发送到服务器。服务器发送回声。

在您的实际应用程序中,您必须查看编码

服务器

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

    }
}

【讨论】:

  • 感谢您的解决方案。你能指出为什么我的程序没有做这件事吗?
  • @arindrajit 是的,我在这里。对不起,但我没有整天等待来自 stackoverflow 的问题。您的错误在您的客户程序中。有一个循环while ((b = bfINPUT.read()) != -1) {。这个循环一直等到服务器关闭输入流(但这永远不会发生)。您的客户永远不会离开这个循环。这就是我们需要不同线程来读取文章的原因,因为两者可能同时发生。希望对您有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多