欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-23 18:32:04
客户端复制代码 代码如下:import java.io.bufferedreader;import java.io.inputstreamreader;import jav...

客户端

复制代码 代码如下:

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(); 
    }