유블로그

[Java] network / socket programming 본문

Java

[Java] network / socket programming

yujeong kang 2020. 8. 23. 21:08

- Server

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class NetworkSimpleServer {

	public static void main(String[] args) {
		int port = 5100;
		
		try (ServerSocket serverSocket = new ServerSocket(port)) {
			
			System.out.println("NetworkSimpleServer Started");
			
			while (true) {
				Socket socket = serverSocket.accept();		// 클라이언트가 socket 객체 만드는 순간 socket 반환
				OutputStream output = socket.getOutputStream();		// 서버에게 요청한 클라이언트에게 보내기
				PrintWriter writer = new PrintWriter(output, true);	// 문자 전용 출력 클래스
				writer.println("Hi!");						// 클라이언트에게 전송됨
			}
			
		 } catch (IOException e) {
			 System.out.println("NetworkSimpleServer exception: " + e.getMessage());
			 e.printStackTrace();
		 }
		
		 System.out.println("NetworkSimpleServer Ended");
	}
}

 

- Client

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

public class NetworkSimpleClient {

	public static void main(String[] args) {
		String host = "localhost";
		int port = 5100;
		
		try ( Socket socket = new Socket(host, port) ) {
			
			InputStream input = socket.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
 
            String message = reader.readLine();
            System.out.println(message);
			
		 } catch ( IOException e) {
			 System.out.println("NetworkSimpleClient exception: " + e.getMessage());
			 e.printStackTrace();
		 }
	}
}

'Java' 카테고리의 다른 글

[Java] swea 2105 디저트카페  (0) 2021.04.19
[Java] array to set 그리고 hex to int , int to hex  (0) 2020.10.03
[Java] Collections.sort()  (0) 2020.08.23
[Java] Priority Queue 사용법  (0) 2020.08.23
[Java] jdbc로 DB 사용하기  (0) 2020.08.20