본문 바로가기

JAVA/기초 프로그래밍

쓰레드//어레이리스트//채팅

Server

Main

package main;
public class mainClass {
	public static void main(String[] args) {	
    Socket clientsocket = null;
		List<Socket> list = new ArrayList<Socket>();
		
		try {
			// 문지기 소켓
			// 192.168.7.66			
			ServerSocket serSocket = new ServerSocket(9000);
			// IP, Port 설정 
			// binding(적용)
			// listen
			
			while(true) {
			
				// client를 기다림
				System.out.println("접속 대기중...");
				clientsocket = serSocket.accept();
				
				list.add(clientsocket);
				
				System.out.println("client IP:" + clientsocket.getInetAddress() 
									+ " Port:" + clientsocket.getPort());				
					
				new ServerThread(clientsocket, list).start();
			}
			
		//	clientsocket.close();
		//	serSocket.close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

Thread

package thread;
public class ServerThread extends Thread {
	Socket clientsocket;
	List<Socket> list;
	
	public ServerThread(Socket clientsocket, List<Socket> list) {
		this.clientsocket = clientsocket;	// 자기 자신의 Socket
		this.list = list;					// Socket의 묶음
	}
	@Override
	public void run() {		
		super.run();
		
		try {
			while(true) {
				BufferedReader reader 
					= new BufferedReader(new InputStreamReader(clientsocket.getInputStream()));
				String packetStr = reader.readLine();	// 실제 수신	
				
				System.out.println("클라이언트로부터 패킷:" + packetStr);
				
				// send (보내다)	
				for (int i = 0; i < list.size(); i++) {					
					Socket soc = list.get(i);
					if(clientsocket != soc) {
						PrintWriter writer = new PrintWriter(soc.getOutputStream());
						writer.println(packetStr);		// 실제 송신
						writer.flush();
						}
					}
				Thread.sleep(100);
				}
					}catch (Exception e) {
				System.out.println("연결이 끊긴 IP : " + clientsocket.getInetAddress());
				list.remove(clientsocket);//index number가 아닌 Object로 지움
				
				//남은 client 확인
				for (Socket s : list) {
					System.out.println("접속되어 있는 IP : " + s.getInetAddress() 
											+ "  Port : " + s.getPort());
				}
				
				try {
					clientsocket.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
		}
	}
}

 


Client

Main

package main;
public class mainClass {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
														// 127.0.0.1 <- 자기 자신을 접속	
		InetSocketAddress sockAddr = new InetSocketAddress("192.168.7.55", 9000);
		
		Socket socket = new Socket();
		
		try {
			socket.connect(sockAddr, 10000);
			
			InetAddress inerAddr;	// 접속 확인용
			if((inerAddr = socket.getInetAddress()) != null) {
				System.out.println("Server connect success! : " + inerAddr);
			}else {
				System.out.println("Server connect fail~");
			}
			new ReadThread(socket).start();
			
			while(true) {
			
				System.out.print("보낼문자열:");
				String packetStr = sc.next();
				
				// send (보내다)
				PrintWriter writer = new PrintWriter(socket.getOutputStream());
				writer.println(packetStr);
				writer.flush();
				
				/*
				// recv (받는다)
				BufferedReader reader 
					= new BufferedReader(new InputStreamReader(socket.getInputStream()));
				packetStr = reader.readLine();
			
				System.out.println("서버로부터 패킷:" + packetStr);
				*/
			}
		//	socket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

 

Thread

package thread;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class ReadThread extends Thread {
	Socket socket;
	
	public ReadThread(Socket socket) {
		this.socket = socket;
	}
	@Override
	public void run() {		
		super.run();
		try {
			while(true) {
				// recv (받는다)
				BufferedReader reader 
					= new BufferedReader(new InputStreamReader(socket.getInputStream()));
				String packetStr = reader.readLine();			
			
				System.out.println("서버로부터 패킷:" + packetStr);
				
				Thread.sleep(100);
			}
		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

'JAVA > 기초 프로그래밍' 카테고리의 다른 글

ID입력받아 채팅창에서 채팅하기  (0) 2020.06.16
쓰레드 기본개념  (0) 2020.06.15
쓰레드// Object  (0) 2020.06.15
쓰레드 예)  (0) 2020.06.15
TCP// 쓰레드 문자열 전송 기본  (0) 2020.06.15