Android 中 Socket的简单用法

Socket通常也称做”套接字“,用于描述IP地址和端口,废话不多说,它就是网络通信过程中端点的抽象表示。值得一提的是,Java在包java.net中提供了两个类Socket和ServerSocket,分别用来表示双向连接的客户端和服务端。这是两个封装得非常好的类,使用起来很方便!

下面将首先创建一个SocketServer的类作为服务端如下,该服务端实现了多线程机制,可以在特定端口处监听多个客户请求,一旦有客户请求,Server总是会创建一个服务纯种来服务新来的客户,而自己继续监听。程序中accept()是一个阻塞函数,所谓阻塞性方法就是说该方法被调用后将等待客户的请求,直到有一个客户启动并请求连接到相同的端口,然后accept()返回一个对应于客户的Socket。这时,客户方和服务方都建立了用于通信的Socket,接下来就是由各个Socket分别打开各自的输入、输出流。

SocketServer类,服务器实现:

package HA.Socket;

import java.io.*;
import java.net.*;

 public class SocketServer {
    
    ServerSocket sever;
    
    public SocketServer(int port){
        try{
            sever = new ServerSocket(port);
        }catch(IOException e){
            e.printStackTrace();
        }
    }
    
    public void beginListen(){
        while(true){
            try{
                final Socket socket = sever.accept();
                
                new Thread(new Runnable(){
                    public void run(){
                        BufferedReader in;
                        try{
                            in = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
                            PrintWriter out = new PrintWriter(socket.getOutputStream());
                            while (!socket.isClosed()){
                                String str;
                                str = in.readLine();
                                out.println("Hello!world!! " + str);
                                out.flush();
                                if (str == null || str.equals("end"))
                                    break;
                                System.out.println(str);
                            }
                            socket.close();
                        }catch(IOException e){
                            e.printStackTrace();
                        }
                    }
                }).start();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }
}

SocketClient类,客户端实现:

package HA.Socket;

import java.io.*;
import java.net.*;

 public class SocketClient {
    static Socket client;
    
    public SocketClient(String site, int port){
        try{
            client = new Socket(site,port);
            System.out.println("Client is created! site:"+site+" port:"+port);
        }catch (UnknownHostException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    
    public String sendMsg(String msg){
        try{
            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            PrintWriter out = new PrintWriter(client.getOutputStream());
            out.println(msg);
            out.flush();
            return in.readLine();
        }catch(IOException e){
            e.printStackTrace();
        }
        return "";
    }
    public void closeSocket(){
        try{
            client.close();
        }catch(IOException e){
            e.printStackTrace();
        }
    }
    public static void main(String[] args) throws Exception{
        
    }

}

接下来就是来测试Socket通信了!
先运行TestSocketServer类,打开服务端,在12345端口处监听!

package HA.Socket;

 public class TestSocketServer {
    
    public static void main(String[] argvs){
        SocketServer server = new SocketServer(12345);
        server.beginListen();
    }
}

再运行TestSocketClient类:

package HA.Socket;

 public class TestSocketClient {

    public static void main(String[] args){
        
        SocketClient client = new SocketClient("127.0.0.1",12345);
        System.out.println(client.sendMsg("nimei1"));
        client.closeSocket();
        
        SocketClient client1 = new SocketClient("127.0.0.1",12345);
        System.out.println(client1.sendMsg("nimei1111"));
        client1.closeSocket();
        
        SocketClient client11 = new SocketClient("127.0.0.1",12345);
        System.out.println(client11.sendMsg("nimei11111111"));
        client11.closeSocket();
        
        SocketClient client111 = new SocketClient("127.0.0.1",12345);
        System.out.println(client111.sendMsg("nimei11111111111111111"));
        client111.closeSocket();
        
    }
}

输出结果如下:

服务端:

Client is created! site:127.0.0.1 port:12345
Hello!world!! nimei1
Client is created! site:127.0.0.1 port:12345
Hello!world!! nimei1111
Client is created! site:127.0.0.1 port:12345
Hello!world!! nimei11111111
Client is created! site:127.0.0.1 port:12345
Hello!world!! nimei11111111111111111

客户端:

nimei1
nimei1111
nimei11111111
nimei11111111111111111