올해는 머신러닝이다.
자바 멀티서버 기본소스 본문
import java.net.*;
import java.io.*;
import java.util.*;
public class MultiChatServer
{
public static void main(String[] args)
{
try
{
ServerSocket serverSoc = new ServerSocket(10001);
System.out.println("접속을 기다립니다.");
HashMap hm = new HashMap();
while(true)
{
Socket sock = serverSoc.accept();
ChatThread chatthread = new ChatThread(sock,hm);
chatthread.start();
}
}
catch (Exception ex)
{
System.out.println(ex);
}
System.out.println("Hello World!");
}
}
class ChatThread extends Thread
{
private Socket socket;
private String id;
private BufferedReader br;
private PrintWriter pw;
private HashMap hm;
private boolean initFlag = false;
public ChatThread(Socket socket,HashMap hm)
{
this.socket = socket;
this.hm = hm;
try
{
pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//System.out.println("11111");
id=br.readLine();
//System.out.println("22222");
broadcast(id +"님이 접속했습니다.");
System.out.println("접속한 사용자의 아이디는 "+ id +"입니다.");
synchronized(hm)
{
hm.put(this.id,pw);
}
initFlag = true;
}
catch (Exception ex)
{
//System.out.println("111111111");
ex.printStackTrace();
}
}
public void run()
{
try
{
String line = null;
System.out.println("1111111111");
while((line = br.readLine()) != null)
{
broadcast(id + ":" +line);
}
System.out.println("22222222222");
}
catch (Exception ex)
{
//System.out.println("2222222");
ex.printStackTrace();
}
finally
{
synchronized(hm)
{
hm.remove(id);
}
try
{
if(socket!=null)
socket.close();
}
catch (Exception ex)
{
}
}
}
public void broadcast(String msg)
{
synchronized(hm)
{
Collection col = hm.values();
Iterator iter = col.iterator();
while(iter.hasNext())
{
PrintWriter pw = (PrintWriter)iter.next();
pw.println(msg);
pw.flush();
}
}
}
}
'자바 > 채팅방' 카테고리의 다른 글
swing으로 만든 멀티채팅소스 (0) | 2010.10.27 |
---|---|
멀티서버네번째소스 (0) | 2010.10.26 |
자바 멀티채팅클라이언트 기본소스 (0) | 2010.10.24 |
채팅방클라이언트 (0) | 2010.10.22 |
채팅방 Client UI (0) | 2010.10.21 |