网络通信编程二

网络通信编程V2

远程建立通信连接:

以本地电脑演示

接收端

public class Server {
    public void listneConnect(){
        try {
            ServerSocket sc =new ServerSocket(58888);
            //使用while循环不断接收
            while(true){
                System.out.println("Listening.....");
                Socket accept = sc.accept();
                System.out.println("Connect :"+accept.getInetAddress());//建立接收
                InputStream in = accept.getInputStream();
                //接收发送字节数量
                int msglength=in.read();
                //接收发送过来的字节
                byte[] bytes = new byte[msglength];
                for (int i = 0; i < msglength; i++) {
                    bytes[i]= (byte) in.read();
                }
                //将收到的字节解析为字符串
                System.out.println("get:"+new String(bytes));
                
                accept.close();
                in.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    public static void main(String[] args) {
       new Server().listneConnect();
    }
}

发送端

public class Client {
    public static void main(String[] args) {
        try {
            //确定目标ip地址和端口
            Socket sc =new Socket("127.0.0.1",58888);
            OutputStream os = sc.getOutputStream();
            String msg="我是某某某";
			//将字符串转为字节存入字节数组
            byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);
            
            int msglength= bytes.length;
            //写入长度信息
            os.write(msglength);
			//发送字节信息
            for (int i = 0; i < msglength; i++) {
                os.write(bytes[i]);
            }
            os.flush();
            os.close();
            sc.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

1.通信建立链接 只需要你把 IP+port写对

2.如果需要传输数据,一定要提前约定好消息体的协议,如发送文字 数字 等

3.发送一句话则是发送这句话占用多少字节和具体的字节内容并转化为正确的内容

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值