TCP传接数据

TCP传送数据

  1. 创建客户端的Socket对象

    Socket(String host,int port)

  2. 获取输出流OutPutStream

    OutPutStream getOutPutStream()

  3. 写数据

    getOutPutStream().write()

  4. 释放资源

    close

    public class SendDemo {
       public static void main(String[] args) throws IOException {
           Socket s=new Socket("192.168.101.1",12345);
           OutputStream outputStream = s.getOutputStream();
           outputStream.write("hello,world".getBytes());
           outputStream.close();
      }
    }

     

TCP接收数据

  1. 创建服务器端ServerSocke对象

    ServerSocket(int port)

  2. 监听客户端连接,返回一个Socket对象

    Socket accpet()

  3. 获取输入流InputStream

    InputStream getInputStream()

  4. 释放资源

    close

    public class ReceiveDemo {
       public static void main(String[] args) throws IOException {
           ServerSocket s = new ServerSocket(12345);
           Socket socket = s.accept();
           InputStream inputStream = socket.getInputStream();
           byte[] b = new byte[1024];
           int len = inputStream.read(b);
    //       while((len=inputStream.read())!=-1){
    //           String s1 = new String(b, 0, len);
    //           System.out.println("数据是"+s1);
    //       }
           String s1 = new String(b, 0, len);
           System.out.println("数据是" + s1);
           socket.close();
           inputStream.close();
      }
    }

     

  5.  

上一篇:一句代码实现批量数据绑定[下篇]


下一篇:TCP文件上传