TcpServer / Client

항상 정리하기·2022년 6월 12일
0
public class TcpServer {

	public void run(int port) {
		try (ServerSocket serverSocket = new ServerSocket(port)) {
			System.out.println("Server is listening on port " + port);

			while (true) {
				Socket socket = serverSocket.accept();
				System.out.println("[ " + socket.getInetAddress() + " ] client connected");
				OutputStream output = socket.getOutputStream();
				PrintWriter writer = new PrintWriter(output, true);
				writer.println(new Date().toString());

				InputStream input = socket.getInputStream();
				BufferedReader reader = new BufferedReader(new InputStreamReader(input));
				System.out.println("###### msg : " + reader.readLine());
			}

		} catch (IOException ex) {
			System.out.println("Server exception: " + ex.getMessage());
			ex.printStackTrace();
		}
	}
}
public class TcpClient {

	public void run(String hostname, int port, String data) {
		try (Socket socket = new Socket(hostname, port)) {
			OutputStream out = socket.getOutputStream();
			out.write(data.getBytes());
			InputStream input = socket.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(input));

			String time = reader.readLine();
			System.out.println(time);

		} catch (UnknownHostException ex) {
			System.out.println("Server not found: " + ex.getMessage());

		} catch (IOException ex) {
			System.out.println("I/O error: " + ex.getMessage());
		}
	}
}
profile
늦은 것 같지만 이제부터라도 차근차근 하나씩 정리하기

0개의 댓글