2012-11-14 4 views
2

저는 java를 처음 사용하고 소켓을 사용하는 방법을 배우려고합니다.소켓 및 Java 채팅

나는 간단한 텍스트 메신저 서버 쓰기 위해 노력하고있어 - 클라이언트,하지만 난 서버가 항상 클라이언트의 스트림을 수신하는 방법을 모르는 : 지금은 단지 관리에 의해, 여기

서버 코드의 1 연결이 수신되면 클라이언트는 서버에 메시지를 보냅니다.

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

public class SocketServer { 

private InetAddress ServerAddress; 
private int ServerPort; 
private int ServerQueue; 
private ServerSocket Server; 

public SocketServer(String ServerAddress, int ServerPort, int ServerQueue) 
{ 
    try 
    { 
     this.ServerAddress = InetAddress.getByName(ServerAddress); 
    } 
    catch (UnknownHostException uhe) 
    { 
     uhe.printStackTrace(); 
    } 
    this.ServerPort = ServerPort; 
} 

public boolean ServerCreate() 
{ 
    try 
    { 
     Server = new ServerSocket(this.ServerPort, 10, this.ServerAddress); 
     System.out.println("System Message: Server started!"); 
     return true; 
    } 
    catch(IOException ioe) 
    { 
     ioe.printStackTrace(); 
     System.out.println("System Message: Can't start server!"); 
     return false; 
    } 
} 

public void ServerStartListening() 
{ 
    int exit = -1; 
    while(exit < 1) 
    { 
     try 
     { 
      Socket client = this.Server.accept(); 
      OutputStream clientout = client.getOutputStream(); 
      BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(clientout)); 
      bw.write("Welcome: "+client.toString()); 
      bw.close(); 
     } 
     catch (IOException ex) 
     { 
      ex.printStackTrace(); 
     } 
    } 
} 
} 

죄송합니다.

+1

여러 클라이언트를 수신 대기하려는 목표는 무엇입니까? –

+0

첫 글자 대문자 속성은 –

+0

난 그냥 지금은하고 싶지 .. 혼란 있습니다 : 서버는 메시지를 수신, 클라이언트가 서버에 메시지를 보내 3 - - - 서버 이 시작 은 1 서버가 응답 할 수 또는 다른 메시지를 기다리는 중 ... –

답변

3

여러 들어오는 요청을 수신 대기하려면 멀티 스레딩을 구현해야합니다. 이 link을 참조하십시오 : 오라클의 매우 멋진 다중 스레드 서버 예제

2

sth를 읽어야합니다. 스레드에 대한. 여기에 초기 코드 :

ServerSocket socketListener; 
DoSthWithThisSocket doSthWithThisSocketObj; 
socketListener = new ServerSocket(LISTENINGPORT); 
Socket socket; 
Thread doSthWithThisSocketThread; 

while (continueSocketListening()) { 
    socket = socketListener.accept(); 
    doSthWithThisSocketObj = new DoSthWithThisSocket(socket); 
    doSthWithThisSocketThread = new Thread(doSthWithThisSocketObj); 
    doSthWithThisSocketThread.start(); 
} 
1

자바 멀티 클라이언트 소켓 서버 작업을 수행하는 두 가지 옵션이 있습니다 : 이전의 응답자는 제안으로

    는 각각의 새로운 클라이언트 TCP 연결을위한 새 스레드를 시작
  • 가. 이것은 smallish/toy 서버 및 소켓을 가지고 놀기 시작했을 때 괜찮습니다. 여기서 큰 단점은이 접근법이 확장되지 않는다는 것입니다.
  • Java NIO package에서 제공하는 비 블로킹 소켓에서 IO 멀티플렉싱을 사용하고 등록 된 콜백에 수용/읽기/쓰기 이벤트를 디스 패칭합니다. . 작업 항목 대기열과 미리 할당 된 작업자 스레드 풀을 사용하여이 항목을 확장하여 하드웨어의 여러 코어/CPU를 활용할 수 있습니다.