Language/Java

TCP Socket프로그래밍

원2 2021. 4. 5. 12:46
728x90
반응형

ServerSocket

 

import java.net.*;
import java.io.*;
import java.util.*;
import java.text.SimpleDateFormat;

public class Ex16_6 {

	public static void main(String[] args) {
		ServerSocket serverSocket = null;
		try {
			serverSocket = new ServerSocket(7777);
			// 서버소켓을 생성하여 7777번 포트와 결합시킨다.
			System.out.println(getTime()+"서버가 준비되었습니다."); // getTime 현재시간
		} catch (IOException e) { e.printStackTrace(); }
		
		while (true) { // 무한반복
			try {
				System.out.println(getTime()+ "연결 요청을 기다립니다.");
				
				Socket socket = serverSocket.accept();
				// 서버소켓은 클라이언트의 연결요청이 올 때까지 실행을 멈추고 계속 기다린다.
				// 클라이언트의 연결요청이 오면 클라이언트 소켓과 통신할 새로운 소켓을 생성한다.
				// 3way handshake를 처리  // 대기상태, 블록킹, 서버소켓의 특권
				System.out.println(getTime()+ socket.getInetAddress() +//상대의 Ip 가져옴
																"로 부터 연결요청이 들어왔습니다");
				OutputStream out = socket.getOutputStream(); 
				DataOutputStream dos = new DataOutputStream(out); // dos 출력용
				// 소켓을 출력 스트림을 얻는다.
				
				//dos.writeUTF("[Notice] Test Message1 form Server.");
				System.out.print("전송할 메세지 : ");
				Scanner aScanner = new Scanner(System.in);
				dos.writeUTF(aScanner.nextLine()); // UTF 유니코드를 위한 문자 인코딩방법
				// 원격 소켓에 데이터를 보낸다.
				//객체명.writeUTF(객체명.nextLine) 원래 사용법.
				
				dos.writeUTF("[Notice] Test Message1 form Server.");
				System.out.println(getTime() + "데이터를 전송했습니다.");
				
				dos.close();
				socket.close(); // 스트림과 소켓을 닫아준다.
			} catch (IOException e) {
				e.printStackTrace(); 
			}
		}
	}
	static String getTime() {
		SimpleDateFormat f = new SimpleDateFormat("[hh:mm:ss]");
		return f.format(new Date()); //현재시간을 문자열로 반환하는 함수
	}
}

서버와 클라이언트를 연결
클라이언트소켓

import java.net.*;
import java.io.*;
public class Ex16_7 {

	public static void main(String[] args) {
		try {
			String serverIp = "127.0.0.1"; // 
			// localhost, 루프백, 규약으로 정해둔것. 나와 나를 연결한다. 자신의 컴퓨터를 의미.
			System.out.println("서버에 연결중입니다. 서버 IP :" + serverIp);
			Socket socket = new Socket(serverIp, 7777);
			// 소켓을 생성하여 연결을 요청
			// accept(); 와 연결을 요청하는것이 밑의 부분. 
			
			InputStream in = socket.getInputStream();
			DataInputStream dis = new DataInputStream(in);
			// 소켓의 입력스트림을 얻는다.
			
			System.out.println("서버로부터 받은 메시지 : " + dis.readUTF()); 
			// 서버로 부터 UTF를 읽어온다.
			System.out.println("연결을 종료합니다.");
			//소켓으로 부터 받은 데이터를 출력
			
			dis.close();
			socket.close();
			System.out.println("연결이 종료되었습니다.");
			
		} catch (ConnectException ce) {
			ce.printStackTrace();
		} catch (IOException ie) {
			ie.printStackTrace(); 
		} catch (Exception e) {
			e.printStackTrace();
		}// 스트림과 소켓을 닫는다.
	}

}

UTF는 유니코드로 문자 저장방식

void writeUTF(String str)


String nextLine()


객체명.writeUTF(객체명.nextLine()) 원래 writeUTF쓰는 법.

728x90
반응형

'Language > Java' 카테고리의 다른 글

채팅의 쓰레드화 04번  (0) 2021.04.06
전이중방식 채팅  (0) 2021.04.06
패키지로 묶어서 소켓 돌리기  (0) 2021.04.05
TCP UDP  (0) 2021.04.05
InetAddress 클래스  (0) 2021.04.05
교착상태  (0) 2021.04.02