2017-09-28 5 views
-1

서버와 클라이언트를 사용하여 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()); 
    } 
}} 

답변

0

코드에 약간의 "문제"가 있습니다.

  1. 완료 한 경우에만 ServerSocket을 닫아야합니다.
  2. 새로 연결된 클라이언트를 스레드 내에서 처리해야 여러 클라이언트가 동시에 메시지를 보낼 수 있습니다.

당신은 쉽게 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(); 
} 

이제 프로그램에서 클라이언트를 계속 받아 들여야합니다. 하지만 한 번에 하나씩. 이제 programm을 중지하거나 someCondition을 false로 변경하고 다음 클라이언트를 승인하여 서버를 종료 할 수 있습니다.

더 진보 된 방법은 ServerSocket을 종료하여 while 루프 내에서 programm를 중지하고 예외를 catch하는 것입니다.

2.


는 다른 스레드에 핸들 부분을 포장한다, 여러 클라이언트가 simultaniously 처리 할 수 ​​있도록합니다.

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

threadPool.submit 블록 내의 일부 method reference을 사용하여 호출하는 등의 방법을 실행 가능한 인터페이스의 정의 인스턴스로 지정 될 수있다.
ThreadPools에 대해 알고 있다고 가정했습니다. They have multiple advantages over Threads

이렇게하면 원하는만큼의 클라이언트를 확보 할 수 있습니다.

참고 : 이것은 잘 설계된 것은 아니지만 데모 용 porpurses 전용입니다.