java2019. 9. 22. 22:43

Socket 및 In/Out stream 다루는 부분을 중점적으로 확인

 

Socket과 InputStream, OutputStream을 사용한다는 것을 기억.

 

ex)

public class SocketTest {
	
	
	public SocketTest() {
		super();
		
		new Thread() {
			public void run() {				
				ServerTestSampleRun();
			};
		}.start();
		
		new Thread() {
			public void run() {				
				ClientTestSampleRun();
			};
		}.start();
		
		
	}

	
	private void ServerTestSampleRun() {
		ServerSocket server = null;
		Socket client= null;
		
		
		
		try {
			
			server = new ServerSocket(9999);//server 객체 생성
			
			while(true) {
				
				System.out.println("server : Waiting for request...");
				client = server.accept();//socket 생성 후, client의 연결을 대기
				
				System.out.println("server : accepted");
				
				InputStream stream = client.getInputStream();//client로 부터의 메세지를 받기 위한stream
				BufferedReader  in = new BufferedReader(
						new InputStreamReader(stream));//문자열 처리를 위해 사용
				String data = null;
				StringBuilder receivedData = new StringBuilder();
				
				while((data = in.readLine())!=null){
					receivedData.append(data);
				}
				System.out.println("received data : "+receivedData.toString());
				
				
				in.close();
				stream.close();
				client.close();
				
				if(receivedData!=null && "EXIT".equals(receivedData.toString())) {
					System.out.println("stop SocketServer");
					break;
				}
				
				System.out.println("-------");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if( server != null)
					server.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
		
	}

	
private void ClientTestSampleRun() {
		
		
		for ( int loop = 0 ; loop < 3 ; loop++) {
			sendSocketData("I hate java at "+ new Date());
		}
		
		sendSocketData("EXIT");
	}

	private void sendSocketData(String data) {
		Socket socket = null;
		try {
			System.out.println("client : connecting...");
			socket = new Socket("127.0.0.1", 9999);//socket을 만드는 것만으로도 연결이 수행
			System.out.println("client : connect status = "+socket.isConnected());
			
			Thread.sleep(1000);
			OutputStream stream = socket.getOutputStream();//server로 데이터 전송을 위한 stream을 가져옴.
			BufferedOutputStream out=
					new BufferedOutputStream(stream);
			byte[] bytes = data.getBytes(); 
			out.write(bytes);
			
			System.out.println("client : send data");
			out.close();
			
			 Thread.sleep(3000);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				socket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

}

출처 : 자바의 신

Posted by easy16