클래스
ClientThread - 클라이언트 측 사용자 정의 스레드 클래스. 서버에서 전송한 문자열을 읽는 역할을 한다.
ServerThread - 서버 측 사용자 정의 스레드 클래스. 클라이언트에서 전송한 문자열을 다시 전송하는 역할을 한다.
SimpleClient - 클라이언트 클래스. ClientThread를 Start 시키고, 사용자로부터 문자열을 입력받아 서버로 전송하는 역할을 한다.
SimpleServer - 서버 클래스. ServerThread를 Start 시키고, 클라이언트의 접속을 기다리는 역할을 한다.
소스
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
public class ServerThread implements Runnable{
private String clientID = null;
private Socket socket = null;
private BufferedReader br = null;
private PrintWriter out = null;
public ServerThread(Socket socket){
this.socket = socket;
}
public void joinClient() {
try{
clientID = br.readLine();
if(clientID==null||clientID.equals(" ")) {
clientID = "손님_" + Math.random();
}
}catch(IOException ioe) {
}finally{
SimpleServer.addClient(this);
String msg = SimpleServer.msgKey + clientID + "님이 입장하셨습니다.";
SimpleServer.broadCasting(msg);
System.out.println(msg);
}
}
public void exitClient() {
SimpleServer.removeClient(this);
String msg = SimpleServer.msgKey + clientID + "님이 퇴장하셨습니다.";
SimpleServer.broadCasting(msg);
System.out.println(msg);
}
//클라이언트와 연결된 출력스트림을 통해 출력하는 메소드
public void sendMessage(String message){
out.println(message);
}
public void run(){
try{
//1. 소켓을 통해 스트림 생성(Input, Output)
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
joinClient();
//2. 클라이언트가 보낸 글을 읽어 들인다.
String str = br.readLine();
String strResult = null;
while(str!=null) {
//3. 클라이언트가 보낸 글이 있는 동안 SimpleServer의 broadCasting()메소드를 통해 연결된 모든 클라이언트들에게 글을 전송한다.
strResult = SimpleServer.broadCasting(clientID, str);
System.out.println(strResult);
str = br.readLine();
}
}catch (IOException e) {
// e.printStackTrace();
}finally{
//4. io, socket 연결을 종료한다.
if(br!=null) {
try{br.close();}catch(IOException ioe){}
}
if(out!=null) {
out.close();
}
if(socket!=null) {
try{socket.close();}catch(IOException ioe){}
}
//5. SimpleServer의 removeClient() 를 통해 자기 자신을 대화대상에서 제거 한다.
exitClient();
}//end of finally
}
}
--------------------------------------------------------------------------------import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class SimpleServer{
public static final String msgKey = "알림) ";
//연결된 클라이언트들의 정보를 저장하는 ArrayList - 대화대상목록(List)
private static ArrayList<ServerThread> list = new ArrayList<ServerThread>();
//private static HashMap<String, ServerThread> map = new HashMap<String, ServerThread>();
//클라이언트를 대화대상목록에서 제거하는 메소드
//ServerThread에서 클라이언트와 연결이 종료될 때 호출한다.
public static void removeClient(ServerThread st){
list.remove(st);
}
//연결한 클라이언트를 대화대상목록에 추가하는 메소드
//클라이언트와 연결될때 호출된다.
public static void addClient(ServerThread st){
list.add(st);
}
//대화대상목록의 모든 클라이언트들에게 인수로 받은 글을 전송하는 메소드
//클라이언트가 보낸 메세지(글)이 있을때 ServerThread로 부터 호출된다.
public static void broadCasting(String message){
ServerThread st = null;
for(int i=0; i<list.size(); i++) {
st = list.get(i);
st.sendMessage(message);
}
}
public static String broadCasting(String clientID, String message){
String sendMSG = clientID + ": " + message;
ServerThread st = null;
for(int i=0; i<list.size(); i++) {
st = list.get(i);
st.sendMessage(sendMSG);
}
return sendMSG;
}
public static void main(String args[]) {
ServerSocket ss=null;
Socket socket = null;
int i=0;
try{
System.out.println("<Lee Wan-Geun's Simple Chatting Server>");
//1. server 소켓생성
ss = new ServerSocket(5000);
while(true) {
//2. 클라이언트의 연결을 무한 반복하며 기다린다.
System.out.println(msgKey + "클라이언트 연결을 대기 중입니다.");
socket = ss.accept();
//3. 클라이언트가 연결되면 ServerThread를 생성한 뒤 Thread로 실행시킨다.
ServerThread st = new ServerThread(socket);
Thread t = new Thread(st);
t.start();
//4. 연결된 클라이언트의 정보(ServerThread)를 대화대상목록(ArrayList)에 추가 시킨다.'
// ServerThread에서 추가
}
}catch(IOException ioe){
ioe.printStackTrace();
}finally{
if(socket!=null) {
try{socket.close();}catch(IOException ioe){}
}
}
}//end of method
}
--------------------------------------------------------------------------------
import java.net.Socket;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ClientThread implements Runnable
{
Socket socket = null;
public ClientThread(Socket socket) {
this.socket = socket;
}
public void run() {
if(socket!=null) {
BufferedReader br = null;
try{
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str = br.readLine();
while(str!=null) {
System.out.println(str);
str = br.readLine();
}
System.out.println(">>> Client Thread end");
}catch(IOException ioe){
// ioe.printStackTrace();
}finally{
if(br!=null) {
try{br.close();}catch(IOException ioe){}
}
if(socket!=null){
try{socket.close();}catch(IOException ioe){}
}
}
}
else {
System.out.println("Client Socket is null");
}
}
}
--------------------------------------------------------------------------------
import java.net.*;
import java.io.*;
public class SimpleClient { public static String enterName(BufferedReader br, PrintWriter out) {
String str = null;
try{
System.out.print("대화명 입력: ");
str = br.readLine();
out.println(str);
}catch(IOException ioe) {
ioe.printStackTrace();
}
return str;
} public static void main(String[] args) {
Socket socket = null;
BufferedReader keyboard = null;
PrintWriter out = null;
try{
// 1. 서버와 연결 작업을 처리 - socket 생성
socket = new Socket("127.0.0.1", 5000);
// 2. 서버가 보낸 글을 읽는 ClientThread 객체 생성, 실행
ClientThread ct = new ClientThread(socket);
Thread t = new Thread(ct);
t.start();
// 3. 키보드로 부터 글을 읽고 서버에 전송.
keyboard = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(socket.getOutputStream(), true);
enterName(keyboard, out);
String str = keyboard.readLine();
while(str!=null){
out.println(str); // 서버 전송
str = keyboard.readLine(); // 키보드에서 읽기
}
}catch(IOException ioe){
ioe.printStackTrace();
}finally{
// 4. 스트림과 소켓의 연결을 끊는다.
if(keyboard!=null) {
try{keyboard.close();}catch(IOException ioe){}
}
if(out!=null) {
out.close();
}
if(socket!=null) {
try{socket.close();}catch(IOException ioe){}
}
}
}
}
'개발 > java' 카테고리의 다른 글
class 란...무엇인가... (0) | 2013.10.22 |
---|---|
걍 뻘짓. (0) | 2013.10.22 |
다중 소켓 관리(접속자인원 멀티로) (1) | 2013.10.17 |
elementAt(); 메소드 사용법 (0) | 2013.10.17 |