TCP通信练习1(服务器给出反馈)

客户端

package com.inetTes01;
/*
客户端:发送数据,接收服务器反馈

 */

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

public class ClientDemo {
    public static void main(String[] args) throws IOException {
        //创建客户端的Socket对象(Socket)
        Socket s = new Socket("192.168.18.6", 10000);

        //获取输出流,写数据
        OutputStream os = s.getOutputStream();
        os.write("你好吗,我来了服务器端".getBytes());
        

//        接收服务器反馈,相当于读取数据
        InputStream is = s.getInputStream();
        byte[] bys = new byte[1024];
        int len = is.read(bys);
        System.out.println("客户端:" + new String(bys, 0, len));

        //释放资源  因为is,os 都是通过s得到的不需要再释放
        s.close();


    }
}

服务器

package com.inetTes01;
/*
接收数据,给出反馈
 */

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

public class ServerDemo {
    public static void main(String[] args) throws IOException {
        //创建服务器端的Socket对象(ServerSocket)
        ServerSocket ss = new ServerSocket(10000);


        //获取输入流,读数据
//       ServerSocket类下的 accept​() 侦听要连接到此套接字并接受它。
        Socket s = ss.accept();
//        获取输入流
        InputStream is = s.getInputStream();
//        读数据
        byte[] bys = new byte[1024];
        int len = is.read(bys);
        System.out.println("服务器" + new String(bys, 0, len));


        //给出反馈,相当于写数据
        OutputStream os = s.getOutputStream();
        os.write("数据已经收到".getBytes());


        //释放资源
        ss.close();


    }
}

 

转载于:https://www.cnblogs.com/lsswudi/p/11440386.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值