先写接收端:

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

public class ServerTcp {

    /**
     * @author xiaozhazi
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        //1.create one ServerSocket and monitor the port
        ServerSocket ss=new ServerSocket(10004);
        
        //2.get the Socket that client-side send
        Socket s=ss.accept();
        
        //3.get the inputStream  by socket
        InputStream in =s.getInputStream();
        String ip=s.getInetAddress().getHostAddress();
        System.out.println(ip+"---has connected");
        
        //4read the data
        byte[] buf= new byte[1];
        int len=-1;
        while((len=in.read(buf))!=-1){
            System.out.print(new String(buf, 0, len));
        }
        
        //close
        s.close();
        
        

    }

}

写客户端

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

public class ClientTcp {
    /**
     * @author xiaozhazi
     * @param args
     * @throws IOException
     * @throws UnknownHostException
     */
    public static void main(String[] args) throws UnknownHostException, IOException {
        //1.create the Socket service
        Socket s=new Socket("192.168.2.36", 10004);
        
        
        //2.get the outputstream by this you can send data to server
        OutputStream out =s.getOutputStream();
        
        //3.send data
        out.write("xiao zha zi dashi".getBytes());
        
        //4.close
        s.close();
    
    }
}