基于TCP协议的Socket通信案例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ITzhongzi/article/details/84629121

客户端代码

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

public class Main {
    public static void main(String[] args) throws IOException {
        Socket s = new Socket(InetAddress.getByName("SKY-20180725WBH"), 10077);
        OutputStream os = s.getOutputStream();
        String str = "hello tcp, i am coming.";
        os.write(str.getBytes());
        os.close();
        s.close();
    }
}

服务端代码

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

public class Receive {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(10077);
        Socket cs = ss.accept();
        System.out.println(cs);

        InputStream is = cs.getInputStream();
        byte[] bys = new byte[1024];
        int len;
        len = is.read(bys);
        InetAddress address = ss.getInetAddress();
        System.out.println(new String(bys, 0, len));
        System.out.println(cs.getPort());
        System.out.println(cs.getInetAddress());
        System.out.println();
        System.out.println(cs.getPort());
        cs.close();
//        ss.close(); //服务端可以不关
    }
}

运行效果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/ITzhongzi/article/details/84629121