서버와 클라이언트를 사용하여 Java와 네트워킹을 시작했습니다. 내가 무슨 일이 일어나고 있는지에 대한 기본 사항을 이해하고 있지만, 나는 그것을 모두 모아서 제목에서하고 싶은 일을하기 위해 고심하고 있었다. 나는이 메시지를 서버에 보내도록 만들었지 만 사용자로부터 입력 문자열로 메시지를 변환하는 방법과 ID가 클라이언트와 서버간에 여러 메시지를 보내는 방법을 궁금해했습니다. 감사합니다.두 개 이상의 사용자 입력 메시지를 클라이언트와 서버간에 보낼 수 있도록이 코드를 변경하는 방법
서버
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());
}
}}