最简单实现socket编程案例

服务端实现多线程接收请求,在接受到客户端的消息后打印消息并回送消息长度给客户端

客户端实现键盘输入并发送消息给服务端

 

Server.class

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket socket = new ServerSocket(2000);

        System.out.println("服务器准备就绪");
        System.out.println("服务器信息:" + socket.getLocalSocketAddress() + "Port: " + socket.getLocalPort());

        //等待客户端连接
        for(;;){
            //得到客户端
            Socket client = socket.accept();
            //客户端构建异步线程
            //启动线程
            new Thread(new ClientHandler(client)).start();
        }

    }

    /**
     * 客户端消息处理
     */
    private static class ClientHandler implements Runnable{
        private Socket socket;
        private boolean flag = true;

        ClientHandler(Socket socket){
            this.socket = socket;
        }

        @Override
        public void run() {
            System.out.println("新客户端连接:" + socket.getInetAddress() + "Port: " + socket.getPort());

            try {
                //得到打印流,用于数据输出
                PrintStream socketOutput = new PrintStream(socket.getOutputStream());

                //得到输入流,用于接收数据
                BufferedReader socketInput = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                do{
                    String str = socketInput.readLine();
                    if("bye".equalsIgnoreCase(str)){
                        flag = false;
                        socketOutput.println("bye");
                    }else{
                        System.out.println(str);
                        socketOutput.println("回送:" + str.length());
                    }
                }while (flag);

                socketInput.close();
                socketOutput.close();

            }catch (Exception e){
                System.out.println("连接异常断开");
            }finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println("客户端已退出"+socket.getInetAddress() + "Port: " + socket.getPort());
            }
        }
    }
}

Client.class

import java.io.*;
import java.net.Inet4Address;
import java.net.InetSocketAddress;
import java.net.Socket;

public class Client {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket();
        socket.setSoTimeout(3000);

        socket.connect(new InetSocketAddress(Inet4Address.getLocalHost(), 2000),3000);

        System.out.println("已发起对服务器的连接");
        System.out.println("客户端信息:" + socket.getLocalAddress() + "Port:" + socket.getLocalPort());
        System.out.println("服务器信息:" + socket.getInetAddress() + "Port:" + socket.getPort());

        try {
            todo(socket);
        }catch (Exception e){
            System.out.println("异常关闭");
        }finally {
            socket.close();
            System.out.println("客户端已退出");
        }


    }

    private static void todo(Socket client) throws IOException{
        //构建键盘输入流
        InputStream in = System.in;
        BufferedReader input = new BufferedReader(new InputStreamReader(in));

        //得到socket输出流,并转换成打印流
        PrintStream printStream = new PrintStream(client.getOutputStream());

        //得到socket输入流
        BufferedReader socketInput = new BufferedReader(new InputStreamReader(client.getInputStream()));

        boolean flag = true;
        do {
            //从键盘读取并发送
            String str = input.readLine();
            printStream.println(str);

            //从服务器读取一行
            String echo = socketInput.readLine();
            if ("bye".equalsIgnoreCase(echo)) {
                flag = false;
            }else{
                System.out.println(echo);
            }
        }while (flag);

        input.close();
        printStream.close();
        socketInput.close();
    }
}

 

你可能感兴趣的:(JAVA,Socket)