简体   繁体   English

我将如何更改此代码以允许在客户端和服务器之间发送多个用户输入消息

[英]How would i change this code to allow more than one user input message to be sent between the client and server

I've just started with both java and networking with servers and clients.我刚刚开始使用 java 以及与服务器和客户端的网络。 Although i understand the basics of whats going on, i was struggling to put it all together and do what i wanted to do in the title.虽然我了解正在发生的事情的基础知识,但我很难将它们放在一起并做我想做的事情。 I was able to make this to send a message to the server, however i was wondering how i'd turn the message into a input string from the user, and also how id send multiple messages between the client and server thanks我能够通过它向服务器发送消息,但是我想知道如何将消息转换为来自用户的输入字符串,以及 id 如何在客户端和服务器之间发送多条消息,谢谢

SERVER服务器

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

public class Server {

//Main Method:- called when running the class file.
public static void main(String[] args){ 

    //Portnumber:- number of the port we wish to connect on.
    int portNumber = 15882;
    try{
        //Setup the socket for communication and accept incoming communication
        ServerSocket serverSoc = new ServerSocket(portNumber);
        Socket soc = serverSoc.accept();

        //Catch the incoming data in a data stream, read a line and output it to the console
        DataInputStream dataIn = new DataInputStream(soc.getInputStream());
        System.out.println("--> " + dataIn.readUTF());

        //Remember to close the socket once we have finished with it.
        soc.close();
    }
    catch (Exception except){
        //Exception thrown (except) when something went wrong, pushing message to the console
        System.out.println("Error --> " + except.getMessage());
    }
}}

CLIENT客户

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


public class Client {

//Main Method:- called when running the class file.
public static void main(String[] args){ 

    //Portnumber:- number of the port we wish to connect on.
    int portNumber = 15882;
    //ServerIP:- IP address of the server.
    String serverIP = "localhost";

    try{
        //Create a new socket for communication
        Socket soc = new Socket(serverIP,portNumber);

        //Create the outputstream to send data through
        DataOutputStream dataOut = new DataOutputStream(soc.getOutputStream());

        //Write message to output stream and send through socket
        dataOut.writeUTF("Hello other world!");
        dataOut.flush();

        //close the data stream and socket 
        dataOut.close();
        soc.close();
    }
    catch (Exception except){
        //Exception thrown (except) when something went wrong, pushing message to the console
        System.out.println("Error --> " + except.getMessage());
    }
}}

There are some "problems" with your code.您的代码存在一些“问题”。

  1. You should only close the ServerSocket if you are done.如果你完成了,你应该只关闭 ServerSocket。
  2. You should handle the newly connected client inside a thread to allow multiple clients to simultaniously "send messages".您应该在一个线程内处理新连接的客户端,以允许多个客户端同时“发送消息”。

1. 1.

you could easily wrap your code inside an while loop.您可以轻松地将代码包装在 while 循环中。

boolean someCondition = true;
try{
    //Setup the socket for communication and accept incoming communication
    ServerSocket serverSoc = new ServerSocket(portNumber);
    // repeat the whole process over and over again.
    while(someCondition) {
        Socket soc = serverSoc.accept();

        //Catch the incoming data in a data stream, read a line and output it to the console
        DataInputStream dataIn = new DataInputStream(soc.getInputStream());
        System.out.println("--> " + dataIn.readUTF());
    }

    //Remember to close the socket once we have finished with it.
    soc.close();
}

Now your programm should continue to accept clients.现在你的程序应该继续接受客户。 But only one at a time.但一次只有一个。 You can now terminate the Server by stopping the programm or by changing the someCondition to false and accepting the next client.您现在可以通过停止程序或通过将someCondition更改为 false 并接受下一个客户端来终止服务器。

A bit more advanced would be, to shutdown the ServerSocket to stop the programm and catching the exception inside the while loop.更高级的方法是关闭 ServerSocket 以停止程序并在 while 循环中捕获异常。


2. 2.

To allow multiple clients to be handled simultaniously, you should pack the handle part into another Thread.为了让多个客户端同时被处理,你应该将句柄部分打包到另一个线程中。

private ExecutorService threadPool = Executors.newCachedThreadPool();

boolean someCondition = true;
try{
    //Setup the socket for communication and accept incoming communication
    ServerSocket serverSoc = new ServerSocket(portNumber);
    // repeat the whole process over and over again.
    while(someCondition) {
        Socket soc = serverSoc.accept();

            //Catch the incoming data in a data stream, read a line and output it to the console in a new Thread.
        threadPool.submit(() -> {
            DataInputStream dataIn = new 
            DataInputStream(soc.getInputStream());
            System.out.println("--> " + dataIn.readUTF());
        }
    }

    //Remember to close the socket once we have finished with it.
    soc.close();
}

The part inside the threadPool.submit block could be specified as an custom instance of the Runnable interface of as an method, to call it using method reference . threadPool.submit块内的部分可以指定为作为方法的 Runnable 接口的自定义实例,以使用方法引用调用它。
I assumed you are knowing about ThreadPools.我假设您了解 ThreadPools。 They have multiple advantages over Threads 与线程相比,它们具有多种优势

This should get you going for any number of clients.这应该让你去寻找任何数量的客户。

Note: This is not good designed, but it is for demonstrational porpurses only.注意:这不是很好的设计,但它仅适用于示范性的porpurses。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 客户端可以同时向多台服务器发送消息吗? - Can a client send a message to more than one server concurrently? 如果用户输入多个单词,如何 output 向用户发送错误消息并重复以允许他们再次输入单词 - How to output an error message to the user and repeat to allow them to enter the word again if the user enters more than one word 我如何只允许用户在计算器应用程序中输入小数点? - How would I only allow user to input one decimal point in calculator app? 如何使用循环来允许用户选择多个项目? - How do I use a loop to allow the user to select more than one item? 我不明白为什么我的一个客户端程序不能向服务器发送多于一条消息? - I don't understand why one of my client program can't send more than one message to the server? 我如何不断询问用户有效的整数输入,如果输入有多个约束 - How do I keep asking a user for a valid integer input if there is more than one constraint to the input Java:客户端发送的消息与服务器接收的消息之间存在差异 - Java: discrepancy between message sent from client and message received at server 如果用户输入(双)包含多个点 (.),我如何检查? - How Can I Check , If A User Input (Double) Contain More Than One Point (.)? 当发送到服务器的邮件数量更多时,Netty中的客户端未收到邮件 - Message is not received by client in Netty when there are more number of messages sent to Server Java TCP服务器无法从多个客户端接收消息 - Java TCP server cannot receive message from more than one client
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM