史上最简单的socket

 

1. client

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;


public class TcpClient2 {

	/**
	 * @param args
	 * @throws IOException 
	 * @throws UnknownHostException 
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		Socket s = new Socket("192.168.1.120",9998);
		OutputStream os = s.getOutputStream();
		os.write("i will go".getBytes());
		os.close();
		s.close();
	}

}
            

  

2. Server

 

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;


public class TcpServer2 {

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		ServerSocket ss = new ServerSocket(9998);
		System.out.println(ss.getInetAddress());
		Socket s = ss.accept();
		InputStream is= s.getInputStream();
		byte[] buf = new byte[1024];
		int len = is.read(buf);
		System.out.println(new String(buf,0,len));
	}

}

  

转载于:https://www.cnblogs.com/childhooding/p/4806874.html

你可能感兴趣的:(史上最简单的socket)