服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服务器之家 - 编程语言 - JAVA教程 - 简单的java socket客户端和服务端示例

简单的java socket客户端和服务端示例

2019-11-05 11:31java教程网 JAVA教程

这篇文章主要介绍了java的socket客户端和服务端示例,大家参考使用吧

客户端

复制代码代码如下:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class MyClient {  
    public static void main(String[] args) throws Exception {  
        Socket socket = new Socket("localhost", 10000);  
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));  
        PrintWriter out = new PrintWriter(socket.getOutputStream());  
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));  

        while (true) {  
            String msg = reader.readLine();  
            out.println(msg);  
            out.flush();  
            if (msg.equals("bye")) {  
                break;  
            }  
            System.out.println(in.readLine());  
        }  
        socket.close();  
    }  
}  

 

服务端

复制代码代码如下:


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

 

public class MyServer {  
    public static void main(String[] args) throws IOException {  
        ServerSocket server = new ServerSocket(10000);  

        while (true) {  
            Socket socket = server.accept();  
            invoke(socket);  
        }  
    }  

    private static void invoke(final Socket client) throws IOException {  
        new Thread(new Runnable() {  
            public void run() {  
                BufferedReader in = null;  
                PrintWriter out = null;  
                try {  
                    in = new BufferedReader(new InputStreamReader(client.getInputStream()));  
                    out = new PrintWriter(client.getOutputStream());  

                    while (true) {  
                        String msg = in.readLine();  
                        System.out.println(msg);  
                        out.println("Server received " + msg);  
                        out.flush();  
                        if (msg.equals("bye")) {  
                            break;  
                        }  
                    }  
                } catch(IOException ex) {  
                    ex.printStackTrace();  
                } finally {  
                    try {  
                        in.close();  
                    } catch (Exception e) {}  
                    try {  
                        out.close();  
                    } catch (Exception e) {}  
                    try {  
                        client.close();  
                    } catch (Exception e) {}  
                }  
            }  
        }).start();  
    }  
}  

 

 

延伸 · 阅读

精彩推荐