Java中的多个客户端到服务器通信程序

发布于 2024-10-25 18:25:30 字数 1711 浏览 1 评论 0原文

我写了一个服务器-客户端通信程序,效果很好。

客户端模块

import java.io.*;
import java.net.*;

class Client {
    public static void main(String argv[]) throws Exception {
        String sentence;
        String modifiedSentence;
      while(true){
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

        Socket clientSocket = new Socket("myname.domain.com", 2343);

        DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

        System.out.println("Ready");
        sentence = in.readLine();
        out.writeBytes(sentence + '\n');
        modifiedSentence = in.readLine();
        System.out.println(modifiedSentence);
       }
      clientSocket.close();
    }
}

服务器模块

import java.net.*;

public class Server {
    public static void main(String args[]) throws Exception {
        String clientSentence;
        String cap_Sentence;
        ServerSocket my_Socket = new ServerSocket(2343);

        while(true) {
            Socket connectionSocket = my_Socket.accept();
            BufferedReader in = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            DataOutputStream out = new DataOutputStream(connectionSocket.getOutputStream());
            clientSentence = in.readLine();
            cap_Sentence = "Raceived:" +  clientSentence + '\n';
            out.writeBytes(cap_Sentence);
        }
    }
}

上面是单个客户端-服务器通信的代码,现在我想要多个客户端与该服务器交互。我用谷歌搜索它,发现可以通过使用每个客户端与服务器对话的线程来完成,但由于我是初学者,所以我不知道到底如何实现。所以请有人告诉我该怎么做或给我一些想法。

I wrote a server-client communication program and it worked well.

Client module

import java.io.*;
import java.net.*;

class Client {
    public static void main(String argv[]) throws Exception {
        String sentence;
        String modifiedSentence;
      while(true){
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

        Socket clientSocket = new Socket("myname.domain.com", 2343);

        DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

        System.out.println("Ready");
        sentence = in.readLine();
        out.writeBytes(sentence + '\n');
        modifiedSentence = in.readLine();
        System.out.println(modifiedSentence);
       }
      clientSocket.close();
    }
}

Server module

import java.net.*;

public class Server {
    public static void main(String args[]) throws Exception {
        String clientSentence;
        String cap_Sentence;
        ServerSocket my_Socket = new ServerSocket(2343);

        while(true) {
            Socket connectionSocket = my_Socket.accept();
            BufferedReader in = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            DataOutputStream out = new DataOutputStream(connectionSocket.getOutputStream());
            clientSentence = in.readLine();
            cap_Sentence = "Raceived:" +  clientSentence + '\n';
            out.writeBytes(cap_Sentence);
        }
    }
}

The above is the code for a single client - server communication, now I want multiple client to interact with that server. I googled for it and found that it can be done with the use of a thread for each single client to talk to the server, but since I am a beginner I don't know exactly how to implement. So somebody please tell me how to do or give me some idea about it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

猫七 2024-11-01 18:25:30

MainServer 类

public class Server {

    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = null;

        boolean listeningSocket = true;
        try {
            serverSocket = new ServerSocket(2343);
        } catch (IOException e) {
            System.err.println("Could not listen on port: 2343");
        }

        while(listeningSocket){
            Socket clientSocket = serverSocket.accept();
            MiniServer mini = new MiniServer(clientSocket);
            mini.start();
        }
        serverSocket.close();       
    }

}

辅助类

public class MiniServer extends Thread{

    private Socket socket = null;

    public MiniServer(Socket socket) {

        super("MiniServer");
        this.socket = socket;

    }

    public void run(){
            //Read input and process here
    }
            //implement your methods here

}

MainServer class

public class Server {

    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = null;

        boolean listeningSocket = true;
        try {
            serverSocket = new ServerSocket(2343);
        } catch (IOException e) {
            System.err.println("Could not listen on port: 2343");
        }

        while(listeningSocket){
            Socket clientSocket = serverSocket.accept();
            MiniServer mini = new MiniServer(clientSocket);
            mini.start();
        }
        serverSocket.close();       
    }

}

Helper Class

public class MiniServer extends Thread{

    private Socket socket = null;

    public MiniServer(Socket socket) {

        super("MiniServer");
        this.socket = socket;

    }

    public void run(){
            //Read input and process here
    }
            //implement your methods here

}
ヤ经典坏疍 2024-11-01 18:25:30

您想了解一下 Java 并发。这就是一个 Java 程序同时执行多项操作的概念。在较高级别上,您将采用 while(true) { //... } 块并将其作为实现类的 run() 方法的一部分来运行可运行。您将创建 Thread 的实例调用该 run() 方法,可能是您期望的每个客户端一个。

要真正深入地了解 Java 在并发方面提供的所有功能,请查看 Java 并发实践

You want to look into Java concurrency. That's the concept of one Java program doing multiple things at once. At a high level you will be taking your while(true) { //... } block and running it as part of the run() method of a class implementing Runnable. You'll create instances of Thread that invoke that run() method, probably one per client you expect.

For a really good, deep understanding of all that Java offers when it comes to concurrency, check out Java Concurrency in Practice.

梦里°也失望 2024-11-01 18:25:30

好吧,当我做类似的事情时,我实现了一个管理服务器端的侦听器,因此当客户端(客户端可能不需要更改)连接时,服务器启动一个线程来与该客户端一起工作。

while (!stop)
            {
                socket = serverSocket.accept();
                HiloSocket hiloSocket = new HiloSocket(socket, this);
                hiloSocket.start();
            }

当然,HiloSocket 扩展了 Thread,它具有管理客户端的逻辑......

Well, when I do something like that, I implement a listener that manages the server side, so when a client (the client won't probably need changes) connects, the server launch one thread to work with that client.

while (!stop)
            {
                socket = serverSocket.accept();
                HiloSocket hiloSocket = new HiloSocket(socket, this);
                hiloSocket.start();
            }

Of course, HiloSocket extends Thread and it has the logic behind to manage the client...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文