java socket简单实例

个人对socket的理解还不是很深刻,正在学习。
先上传下自己写好的服务端和客户端连接、相应、断开连接的方式。

服务器端

package socket;

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 SocketService {
    static ServerSocket server=null;
    static Socket socket =null;
    static BufferedReader br;  //控制台输入
    static BufferedReader in;  //读取服务端信息输入流
    static PrintWriter writer; //发送给服务端信息的输出流

    class Accepter extends Thread{
        @Override
        public void run() {
            String message="";
            int i=1;
            try {
                do{
                    message = in.readLine();
                    System.out.println("服务端接收信息第"+i+"次接收到信息为:"+message);
                    i++;
                }while (!"exit".equals(message));
                //当客户端输入exit退出后,关闭socket输入流
                //in.close();  //这种关闭流的方法会导致socket关闭
                socket.shutdownInput();
                System.out.println("服务端已停止接收数据");
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
    class Sender extends Thread{
        @Override
        public void run() {
            int i= 1;
            String readLine = "";

            try {
                do{
                    readLine = br.readLine();
                    if(null != readLine){
                        writer.println(readLine);
                        writer.flush();
                    }
                    System.out.println("服务端第"+i+"次发送信息为:"+readLine);
                    i++;
                }while (!"exit".equals(readLine));
                br.close();
                //writer.close(); //采用流关闭方式会导致socket关闭
                socket.shutdownOutput();
                System.out.println("服务端停止发送数据");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //搭建服务器端
    public static void main(String[] args) throws IOException{
        SocketService socketService = new SocketService();
        //1、a)创建一个服务器端Socket,即SocketService
        socketService.oneServer(socketService);
    }


    public  void oneServer(SocketService socketService){
        try{
            try{
                server=new ServerSocket(5209);
                //b)指定绑定的端口,并监听此端口。
                System.out.println("服务器启动成功");
                //创建一个ServerSocket在端口5209监听客户请求
            }catch(Exception e) {
                System.out.println("没有启动监听:"+e);
                //出错,打印出错信息
            }
            try{
                socket=server.accept();
                //2、调用accept()方法开始监听,等待客户端的连接
                //使用accept()阻塞等待客户请求,有客户
                //请求到来则产生一个Socket对象,并继续执行
            }catch(Exception e) {
                System.out.println("Error."+e);
                //出错,打印出错信息
            }
            Sender sender = socketService.new Sender();
            Accepter accepter = socketService.new Accepter();
            br = new BufferedReader(new InputStreamReader(System.in));
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            writer = new PrintWriter(socket.getOutputStream());

            sender.start();
            accepter.start();


        }catch(Exception e) {//出错,打印出错信息
            System.out.println("Error."+e);
        }
    }
}

客户端

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


public class SocketClient {
    static Socket socket;
    static BufferedReader br;  //控制台输入
    static BufferedReader in;  //读取服务端信息输入流
    static PrintWriter writer; //发送给服务端信息的输出流

    class Accepter extends Thread{
        @Override
        public void run() {
            int i= 1;
            String readLine="";
            try {
                do{
                    readLine = in.readLine();
                    if(null != readLine){
                        System.out.println(readLine);
                    }
                    System.out.println("客户端第"+i+"次接收信息为:"+readLine);
                    i++;
                }while(!"exit".equals(readLine));
                //关闭socket输入流
                //in.close();  采用关闭流的方式会导致socket被关闭
                socket.shutdownInput();
                System.out.println("客户端停止接收数据");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    class Sender extends Thread{
        @Override
        public void run() {
            int i= 1;
            String readLine ="";
            try {
                do{
                    readLine = br.readLine();
                    if(null != readLine){
                        writer.println(readLine);
                        writer.flush();
                        System.out.println("客户端第"+i+"次发送信息为:"+readLine);
                        i++;
                    }
                }while (!"exit".equals(readLine));
                //当客户端输入exit后关闭socket输出流
                br.close();
                //writer.close();  采用流的关闭方式会导致socket关闭
                socket.shutdownOutput();
                System.out.println("客户端停止发送数据");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    // 搭建客户端
    public static void main(String[] args) throws IOException {
        try {
            // 1、创建客户端Socket,指定服务器地址和端口
            socket = new Socket("127.0.0.1",5209);
            System.out.println("客户端启动成功");
            SocketClient socketClient = new SocketClient();
            Sender sender = socketClient.new Sender();
            Accepter accepter = socketClient.new Accepter();
            br = new BufferedReader(new InputStreamReader(System.in));
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            writer = new PrintWriter(socket.getOutputStream());

            sender.start();
            accepter.start();


        } catch (Exception e) {
            System.out.println("can not listen to:" + e);// 出错,打印出错信息
        }
    }

}

说明:运行时必须先启动服务端,否则会报连接异常。

总结:1.关闭socket流会导致socket也被关闭,如果只是想关闭输入或者输出流应该使用socket.shutdownInput()或则socket.shutdownOutput()方法去关闭对于的输入输出流。
2.当socket输入输出流都被关闭后,socket就会自动被关闭。

缺点:只能满足单一的客户端和服务端交互,原因在于服务器端只产生了一个socket,用于接收一个客户端的连接。

你可能感兴趣的:(java socket简单实例)