반응형

TcpServer.java


import java.io.*;
import java.net.*;

public class TcpServer {

	public static void main(String[] args) {
		
		   // 서버소켓 변수
	      ServerSocket ss = null;
	      // 접속할 클라이언트 소켓변수
	      Socket socket = null;
	      try {
	         // 서버소켓생성
	         ss = new ServerSocket(9999);
	         System.out.println("서버 대기중 ");
	         while (true) {
	            // 클라이언트가 접속 할때까지 대기하다가 접소하면
	            // 그 정보를 socket에 저장
	            socket = ss.accept();
	            // 클라이언트 정보출력
	            System.out.println("접속자 정보 : " + socket);
	            // 클라이언트에서 보낸 한줄의 메시지를 출력
	            BufferedReader in = new BufferedReader(
	                  new InputStreamReader(
	                        socket.getInputStream()));
	            String msg = in.readLine();
	            System.out.println("보낸 메시지 : "+msg);
	            //클라이언트와의 연결 끊기
	            in.close();
	            socket.close();
	         }

	      } catch (Exception e) {
	         System.out.println(e.getMessage());
	      }

//		
//		// 서버 소켓변수
//		ServerSocket ss =null;
//		
//		// 접속할 클라이언트 소켓 변수
//		Socket socket = null;
//		
//		try{
//			
//			ss = new ServerSocket(9999);
//			System.out.println(" 서버 대기 중 입니다...");
//		
//			while(true){
//				// 클라이언트가 접속할 때까지 기다린다.
//				// 클라이언트가 접속하면 그 정보를 socket 에저장
//				socket = ss.accept();
//				
//				//클라이언트 정보 출력
//				System.out.println(" 접속자 정보 : " + socket);			
//		
//				// 클라이언트에서 보낸 한줄의 메세지를 출력
//				BufferedReader in = 
//						new BufferedReader(
//								new InputStream(
//										socket.getInputStream()));
//				String msg = in.readLine();
//				System.out.println("보낸 메세지 : " + msg);
//				//클라이언트 연결 끊기
//				in.close();
//				socket.close();
//				ss.close();
//			}
//			
//		}catch(Exception e){
//			System.out.println(e.getMessage());
//		}
//		
		
		

	}

}


TcpClient.java


import java.io.*;
import java.net.*;


public class TcpClient {

	public static void main(String[] args) {
		
		// 접속할 서버의 주소를 저장할 변수
		InetAddress ia = null;
		
		// 서버에 접속할 소켓 변수
		Socket socket = null;
		
		// 테이터를 전송할  Write 변수
		PrintWriter out = null;
		
		
		try{
			// 서버 주소생성
			ia = InetAddress.getByName("127.0.0.1");
			// 서버 연결
			socket = new Socket(ia,8888);
			// 서버에 메세지 전송
			out = new PrintWriter(socket.getOutputStream());
			out.println("" + "\n");
			out.flush();
			// 접속 끊기
			socket.close();
			
			
		}catch(Exception e){
			System.out.println(e.getMessage());
		}

	}

}



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

[JAVA] 자신의 ip 확인 및 IP 출력  (0) 2014.11.18
[JAVA] Multicast Server, Client (Socket)  (0) 2014.11.18
[JAVA] UDP Server, Client 만들기 (Socket)  (1) 2014.11.18
[JAVA] swing Frame  (0) 2014.11.18
[JAVA] swing Table 만들기  (2) 2014.11.18

+ Recent posts