I/O流使用Socket通信

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

/*

  • ServerSocket:此类实现服务器套接字

  • ServerSocket(int port)

  • Socket accept() 侦听并接受到此套接字的连接。

  • InetAddress getInetAddress() 返回此服务器套接字的本地地址。
    */
    //服务端
    public class ServerDemo {

    public static void main(String[] args) throws IOException {
    ServerSocket ss = new ServerSocket(10011);

     Socket socket = ss.accept();
     
     InputStream is = socket.getInputStream();
     
     byte[] bys = new byte[1024];
     int len;
     len = is.read(bys);
     
     InetAddress address = socket.getInetAddress();
     String str = new String(bys,0,len);
     System.out.println(address);
     System.out.println(str);
     
     OutputStream os = socket.getOutputStream();
     String s = "How are u?";
     os.write(s.getBytes());
     
     socket.close();
    
     //ss.close();
    

    }

}

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

/*

  • Socket:此类实现客户端套接字

  • Socket(InetAddress address, int port)

  • Socket(String host, int port)
    */
    //客户端
    public class CilentDemo {

    public static void main(String[] args) throws IOException{
    Socket s = new Socket(InetAddress.getByName(“192.168.0.172”), 10011);

     OutputStream os = s.getOutputStream();
     
     String src = "good afternoon";
     
     os.write(src.getBytes());
     
     InputStream is = s.getInputStream();
     byte[] bys = new byte[1024];
     int len;
     //接收数据
     len = is.read(bys);
     String str = new String(bys, 0, len);
     
     System.out.println(str);
     
     s.close();
    

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值