java socket 相关,希望对您有帮助

客户端socket:

package com.example.demo.practice.socket.old;

import cn.hutool.core.date.DateTime;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class OldSocketClient {


    public static Socket connect(int port) {
        try {
            Socket socket = new Socket("localhost",port);
            return socket;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void sendMessage(Socket socket){
        try {
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(("hello world"+ DateTime.now().toTimeStr()).getBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void receiveMessage(Socket socket){
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(()->{
            try {
                InputStream inputStream = socket.getInputStream();
                int i =-1;
                byte[] bytes = new byte[1028];
                while (((i=inputStream.read(bytes))!=-1)){
                    String s = new String(bytes, 0, i);
                    System.out.println("服务端接收数据:=====>"+s);
                }
                System.out.println("客户端端口连接关闭");
            } catch (IOException e) {
                //断开连接会报异常,此处忽略异常
                //throw new RuntimeException(e);
            }
        });

    }
}

服务端socket 代码:

package com.example.demo.practice.socket.old;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class OldSocketServer {


    public static final List<String> list = new ArrayList<>();

    public static void main(String[] args) {
        try {
            startServer(8081);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static void startServer(int port) throws IOException {
        ServerSocket serverSocket = new ServerSocket(port);
        ExecutorService executorService = Executors.newCachedThreadPool();
        while (true) {
            System.out.println("waiting for client");
            Socket accept = serverSocket.accept();
            System.out.println("client connected"+accept.toString());
            if(list.contains(accept.getLocalPort())){
                continue;
            }else{
                System.out.println("此处代码仅仅执行一次");
               list.add(accept.getLocalPort()+"");
            }
            executorService.execute(()->{
                try {
                    InputStream inputStream = accept.getInputStream();
                    int i =-1;
                    byte[] bytes = new byte[1028];
                    while ((i=inputStream.read(bytes))!=-1){
                        String s = new String(bytes, 0, i);
                        System.out.println("服务端接收数据:=====>"+s);
                        accept.getOutputStream().write(s.getBytes());
                    }
                    list.remove(accept.getLocalPort()+"");
                    System.out.println("客户端端口连接关闭");
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            });
        }
    }


}

客户端执行入口:

package com.example.demo.practice.socket.old;

import java.net.Socket;
import java.util.Scanner;

public class OldSocketMain {


    public static void main(String[] args) throws Exception {
        Socket socket = OldSocketClient.connect(8081);
        OldSocketClient.receiveMessage(socket);
        Scanner scanner = new Scanner(System.in);
        System.out.println("请随意输入字符串验证,输入end,退出客户端");
        while (true){
            String s = scanner.nextLine();
            System.out.println("输入的字符串为:"+s);
            if("end".equals(s)){
                System.out.println("退出程序");
                if(!socket.isClosed()){
                    System.out.println("关闭socket");
//                    socket.shutdownInput();
//                    socket.shutdownOutput();
                    socket.close();
                }
                System.out.println("程序退出");
                break;
            }else{
                if(!socket.isClosed()) {
                    OldSocketClient.sendMessage(socket);
                }else{
                    System.out.println("socket已关闭");
                }
            }
        }
        scanner.close();
        System.out.println("程序结束");
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值