java实现socket通讯

访问端:

 public static void main(String[] args) {
//        initSocket();
        testSocket();
    }

public static void testSocket() {
        try {
            String host = "192.168.3.238";
            int port = 8801;
            if (!connectSocket(host, port)) {
                System.out.println("connect fail");
                return;
            }
            if (!sendData("test data".getBytes(StandardCharsets.UTF_8))) {
                return;
            }
            if (!readData()) {
                return;
            }
            System.out.println("return---" + returnData);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static boolean connectSocket(String host, int port) {
        try {
            socket = new Socket();
            SocketAddress address = new InetSocketAddress(host, port);
            socket.connect(address);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    private static boolean closeSocket() {
        if (!socket.isClosed()) {
            try {
                socket.close();
                return true;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    public static boolean sendData(byte[] data) {
        try {
            OutputStream out = socket.getOutputStream();
            out.write(("send data").getBytes(StandardCharsets.UTF_8));
            out.flush();
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
        return true;
    }

    public static boolean readData() {
        try {
            int len = 0;
            byte[] data = new byte[128];
            InputStream in = socket.getInputStream();
            len = in.read(data);
            String instr = new String(data, 0, len);
//            System.out.println("return message" + instr);
            returnData = instr;
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

服务端main:

public static void main(String[] args) {
        byte[] data = new byte[128];
        int len = 0;
        ServerSocket socket = null;
        try {
            socket = new ServerSocket(8801);
            System.out.println("socket 套接字创建成功,等待连接...");

            while (true) {
                Socket con = socket.accept();
                SocketListenThread s_thread = new SocketListenThread(con);
                s_thread.setSocket(con);
                s_thread.start();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket.isClosed()) {
                System.out.println("socket已经关闭");
            }
        }

服务端线程:

public class SocketListenThread extends Thread {

    /**
     * socket
     */
    private Socket socket;

    @Override
    public void run() {
        try {
            sleep(3000);
            int len = 0;
            s_in = socket.getInputStream();
            len = s_in.read(data);
            String in = new String(data, 0, len);
            System.out.println("接收消息" + in);
            if (socket.isClosed()) {
                System.out.println("socket已经关闭1");
            }
            s_ou = socket.getOutputStream();
            s_ou.write((in + "_a").getBytes(StandardCharsets.UTF_8));
            s_ou.flush();
            s_ou.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

说明:服务端会一直运行,等待接收访问,访问端每次访问都占用一个新的线程来处理当次访问

           对于服务端和访问端,InputStream都为读数据内容,OutputSteam都为发送数据,在发送数据时,不要执行out.close();这样会将socket关闭。

          每次读出的数据,都需要byte[]来接收,因为开始为128位,所有如果读的内容不足128,后面会出现乱码,需要截取对应的长度的数据,len = in.read(data);len即为数据真实长度,实际开发中可以自己指定长度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值