自学篇-网络编程TCP(九)



import java.net.*;

import java.io.*;

class TcpClient {
    public static void main(String[] args) throws Exception{
        //1.建立Socket服务
        Socket sk = new Socket("192.168.0.105",10003);
        //2.运用Socket服务的getOutputStream()方法写数据
        OutputStream out = sk.getOutputStream();
        out.write("wo yao xue bian cheng".getBytes());
        //3.关闭资源
        sk.close();
    }
}

class TcpServer{
    public static void main(String[] args) throws Exception{
        //1.建立Socket 服务并监听端口
        ServerSocket ss = new ServerSocket(10003);
        //2.通过accept()方法获取客户端对象
        Socket s = ss.accept();
        String ip = s.getInetAddress().getHostAddress();
        System.out.print("ip="+ip);
        //3.使用客户端对象获取数据
        InputStream in = s.getInputStream();
        byte[] buf = new byte[1024];
        int len = in.read(buf);
        System.out.print(new String(buf,0,len));
        //4.关闭资源
        s.close();
        ss.close();
    }

}


客户端与服务端数据交互

import java.io.*;
import java.net.*;

class  TcpClient{
    public static void main(String[] args) throws Exception{
        Socket sk = new Socket("10.56.192.176",10005);
        OutputStream out = sk.getOutputStream();
        out.write("wo yoa xue biancheng".getBytes());
        
        InputStream in = sk.getInputStream();
        byte[] buf = new byte[1024];
        int len = in.read(buf);
        System.out.print(new String(buf,0,len));

        sk.close();
    }
}

class TcpServer {
    public static void main(String[] args)throws Exception{
        ServerSocket ss = new ServerSocket(10005);
        Socket s = ss.accept();
        String ip = s.getInetAddress().getHostAddress();
        System.out.print("ip=" + ip);
        InputStream in = s.getInputStream();
        byte[] buf = new byte[1024];
        int len = in.read(buf);
        System.out.print(new String(buf,0,len));
        
        OutputStream out = s.getOutputStream();
        out.write("哥们收到".getBytes());

        s.close();
        ss.close();
    }
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值