socket 통신

package socket;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

/**
 * TCP       
 */
public class TCPServerTest {

	public static void main(String[] args) {
		ServerSocket ss = null;
		PrintWriter pw = null;
		BufferedReader  br = null;
		try {
			ss = new ServerSocket(8888);  //     Server        
			
			System.out.println("       8888  ....");
			Socket so = ss.accept();  //         TCP  ,          Socket
			System.out.println("            :" + so.getRemoteSocketAddress());
			//  
			br = new BufferedReader(new InputStreamReader(so.getInputStream()));
			String str = br.readLine();
			System.out.println("    :" + str);
			
			
			//        Socket                     ,       
//			pw = new PrintWriter(new OutputStreamWriter(so.getOutputStream()), true);
//			pw.println("  ,   !   :" + new Date());
			DataOutputStream dis = new DataOutputStream(so.getOutputStream());
			String result = "  ,   !   :" + new Date();
			dis.write(result.getBytes());
			dis.flush();
			
			//PrintStream System.in;       
			
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(null != pw){
				pw.close();
			}
			if(null != br){
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(null != ss){
				try {
					ss.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
	}

}
package socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * TCP      
 */
public class TCPClientTest {

	public static void main(String[] args) {
		Socket s = null;
		BufferedReader  br = null;
		PrintWriter pw = null;
		try {
			s = new Socket("127.0.0.1",8888); //     Socket,      IP            
			// 
			pw = new PrintWriter(new OutputStreamWriter(s.getOutputStream()), true);
			pw.println("  ,   !");
			
			// 
			br = new BufferedReader(new InputStreamReader(s.getInputStream()));
			String str = br.readLine();
			System.out.println("    :" + str); 
			
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			
			if(null != pw){
				pw.close();
			}
			if(null != br){
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(null != s){
				try {
					s.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
	}

}

좋은 웹페이지 즐겨찾기