[英]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.您的代码存在一些“问题”。
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 循环中捕获异常。
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.