旅行·在路上

Java基础:Socket和ServerSocket

2019-08-25  本文已影响0人  书虫大王X

1.Socket类

(1)创建Socket
(2)打开连接到Socket的输入/输出流
(3)按照一定协议对Socket执行读写操作
(4)关闭Socket

Socket(String host, int port)throws UnknownHostException, IOException;
Socket(InetAddress address, int port)throws UnknownHostException, IOException;
Socket(InetAddress address, int port, InetAddress localAddress, int localPort)throws IOException;
Socket(String host, int port, InetAddress localAddress, int localPort)throws IOException;

注意:在套接字建立的时候,如果远程主机不可访问,这段代码就会阻塞很长时间,直到底层操作系统的限制而抛出异常。所以一般在套接字建立后要设置一个超时时间。

Socket socket = new Socket(...);
socket.setSoTimeout(10000); 
// 单位为毫秒
getInetAddress();      远程服务端的IP地址
getPort();          远程服务端的端口
getLocalAddress()      本地客户端的IP地址
getLocalPort()        本地客户端的端口
getInputStream();     返回与调用的套接字相关联的输入流
getOutStream();      返回与调用的套接字相关联的输出流
//最后两个方法很重要
isClosed();            //连接是否已关闭,若关闭,返回true;否则返回false
isConnect();      //如果曾经连接过,返回true;否则返回false
isBound();            //如果Socket已经与本地一个端口绑定,返回true;否则返回false
isConnected();              //判断Socket的连接状态

2.ServerSocket类:

ServerSocket()throws IOException;
ServerSocket(int port)throws IOException;
ServerSocket(int port, int backlog)throws IOException;
ServerSocket(int port, int backlog, InetAddress bindAddr)throws IOException;

(1)创建ServerSocket
(2)监听客户端的连接(accept()方法)
(3)打开连接到ServerSocket的输入/输出流
(4)按照一定协议对ServerSocket执行读写操作
注意:Socket需要自己关闭,但是ServerSocket不需要自己关闭

Socket与ServerSocket的关系

3.实例:

多线程在网络中的运用,代码流程图:


流程图

因为一个线程只能干一件事,不能同时接受键盘的输入又接受客户端(服务器端)输入的数据,使用必须开启一个子线程帮助主线程完成这两个任务,代码如下:

class Client{
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("127.0.0.1",8080);
//        用一个子线程处理服务器端数据
        new Thread(new CilentThread(socket)).start();
//        从终端接收数据,发给客户端
        BufferedReader keyIn = new BufferedReader(new InputStreamReader(System.in));
        PrintStream ps = new PrintStream(socket.getOutputStream());
        String line = null;
        while ((line = keyIn.readLine()) != null){
            ps.println(line);
        }
    }
}
//创建一个客户端的子线程,接收客户端发送的数据
class CilentThread implements Runnable{
    private Socket socket;
    public CilentThread (Socket socket){
        this.socket = socket;
    }
    @Override
    public void run(){
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String line = null;
            while ((line = br.readLine()) != null){
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println("网络出错,请检查");
            System.exit(-1);
        }finally {
                try {
                    if (br != null) {
                        br.close();
                    }
                    if (socket != null){
                        socket.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }
}
class Server{
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(8080);
        Socket socket = ss.accept();
//        创建一个子线程,处理客户端输入数据
        new ServerThread(socket).start();
//        接收终端的输入(字符)
        BufferedReader keyIn = new BufferedReader(new InputStreamReader(System.in));
//        客户端的输出流
        PrintStream ps = new PrintStream(socket.getOutputStream());
//        读取终端的输入,并输出给客户端
        String line = null;
        while ((line = keyIn.readLine()) != null) {
            ps.println(line);
        }
    }
}
//创建一个子线程接收客户端的数据
class  ServerThread extends Thread{
    private Socket socket = null;
    public ServerThread(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String line = null;
            while ((line = br.readLine()) != null){
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println("网络异常,请重新登陆");
//            断开子线程
            System.exit(-1);
        }finally {
            try {
                if (br != null){
                    br.close();
                }
                if (socket != null){
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

上一篇 下一篇

猜你喜欢

热点阅读