Socket编程:简单实现TCP Socket

目录

Socket编程:简单实现TCP Socket_第1张图片

基本实现

●服务器端代码

public class SocketServer {
    private static final int PORT = 8869;//服务器的端口号
    public static void main(String[] args) {
        try {
            ServerSocket server = new ServerSocket(PORT);//开启本地8860端口号
            System.out.println("服务端开启");
            while(true) {//开启循环监听客户端的连接
                Socket client = server.accept();//当有客户端连接的时候获取客户端
                InputStream inputStream = client.getInputStream();//获取客户端的输入流
                OutputStream outputStream = client.getOutputStream();//获取客户端输出流
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String clientMsg = bufferedReader.readLine();
                System.out.println(client.getInetAddress().getHostAddress()+":"+clientMsg);//打印出客户端的地址和消息
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
                bufferedWriter.write("我是服务器端的消息");//发送消息给客户端
                bufferedWriter.newLine();
                bufferedWriter.flush();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}

●客户端代码

public class SocketClient {
    private static final String HOST = "192.168.0.137";//连接的服务器地址
    private static final int PORT = 8869;//连接的服务器端口
    public static void main(String[] args) {
        try {
            Socket client = new Socket(HOST, PORT);//开启连接
            InputStream inputStream = client.getInputStream();//获取输入流
            OutputStream outputStream = client.getOutputStream();//获取输出流
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
            bufferedWriter.write("我是客户端的消息");//向服务器发送消息
            bufferedWriter.newLine();
            bufferedWriter.flush();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String serverMsg = bufferedReader.readLine();//获取服务器发送的消息
            System.out.println("服务器消息:"+serverMsg);//服务器的消息
            client.close();//关闭客户端
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}

●基本实现效果

Socket编程:简单实现TCP Socket_第2张图片

扩展实现

由于这样只是简单的向服务器发送消息,然后服务器返回一条消息就关闭了,接下来我们通过线程来实现服务器与客户端长久通信。
●服务器端代码
每当有客户端连接服务器的时候就开启一个对应的客户端线程,用来与此客户端进行通信。

public class SocketServer {
    private static final int PORT = 8869;//服务器的端口号
    public static void main(String[] args) {
        try {
            ServerSocket server = new ServerSocket(PORT);//开启本地8860端口号
            System.out.println("服务端开启");
            while(true) {//开启循环监听客户端的连接
                Socket client = server.accept();//当有客户端连接的时候获取客户端
                new ClientSocketThread(client).start();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
/**
 * 客户端的线程
 * @author itfitness
 *
 */
public class ClientSocketThread extends Thread {
    private Socket socket;
    //初始化的时候传入Socket
    public ClientSocketThread(Socket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
        
        try {
            InputStream inputStream = socket.getInputStream();//获取客户端的输入流
            OutputStream outputStream = socket.getOutputStream();//获取客户端输出流
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
            String clientMsg = "";
            //当客户端发送的消息不是bye的时候就将消息打印出来
            while(!clientMsg.equals("bye")) {
                clientMsg = bufferedReader.readLine();
                System.out.println(socket.getInetAddress().getHostAddress()+":"+clientMsg);//打印出客户端的地址和消息
                bufferedWriter.write("我是服务器端反馈:"+clientMsg);//发送消息给客户端
                bufferedWriter.newLine();
                bufferedWriter.flush();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        super.run();
    }
}

●客户端代码
客户端代码的发送消息和获取消息放在了循环中,发送的消息是键盘输入的,只要发送的消息不是bye就会一直连接服务器。

public class SocketClient {
    private static final String HOST = "192.168.0.137";
    private static final int PORT = 8869;
    public static void main(String[] args) {
        try {
            Socket client = new Socket(HOST, PORT);
            InputStream inputStream = client.getInputStream();
            OutputStream outputStream = client.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            Scanner scanner = new Scanner(System.in);
            String msg = "";
            //当输入的消息不是bye的时候就一直连接
            while(!msg.equals("bye")) {
                if(scanner.hasNext()) {
                    msg = scanner.next();
                    bufferedWriter.write(msg);
                    bufferedWriter.newLine();
                    bufferedWriter.flush();
                    String serverMsg = bufferedReader.readLine();
                    System.out.println("服务器消息:"+serverMsg);//打印出客户端的地址和消息   
                }
            }
            client.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}

●扩展实现效果

Socket编程:简单实现TCP Socket_第3张图片

你可能感兴趣的:(Socket编程:简单实现TCP Socket)