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

Socket多客户端通信

程序员文章站 2024-03-22 23:35:52
...

主要思路

服务端打开端口,客户端连接指定端口,双方打开IO流,之间进行通信

写在最后

通过 accept = serverSocket.accept();是否执行完毕判断有用户连接,因为可能多个用户连接,所以while轮询,此时可以将用户Socket保存下来,方便后期进行通讯。
注意点是在进行通信时发送方发送完数据不能关闭IO流,关闭IO将不能继续通信,而要flush流,将数据发送出去。在调用close方法时会自动flush。
接受数据时用InputStream接受字节流时不会出现length=-1这种情况,因为通道一直打开。并没有关闭。所以要一直读即可。

贴上代码

MyService

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class MyService {
    public static void main(String[] args) {

        ServerSocket serverSocket = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        ArrayList<Socket> arrayList=new ArrayList<Socket>();
        Socket accept = null;
        byte[] bytes = null;

        try {
            serverSocket = new ServerSocket(8888);
            System.out.println("服务端已打开");
            while (true) {
                accept = serverSocket.accept();
                arrayList.add(accept);
                System.out.println("客户端连接成功");
//                new Thread(new ServiceSend(accept)).start();
                new Thread(new ServiceReceive(accept,arrayList)).start();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (accept != null) {
                try {
                    accept.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}

ServiceReceive


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

public class ServiceReceive implements Runnable{
    Socket socket=null;
    InputStream inputStream=null;
    byte[] bytes =new byte[1024];
    ArrayList arrayList=null;
    String str;
    int length;
    public ServiceReceive(Socket socket,ArrayList arrayList) {
        this.socket = socket;
        this.arrayList=arrayList;
    }

    @Override
    public void run() {
        try {
            inputStream=socket.getInputStream();
            length=inputStream.read(bytes);
            while (length!=-1){
                System.out.println(new String(bytes));
                new SendGroup(socket,arrayList,bytes).run();
                length=inputStream.read(bytes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

ServiceSend

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

public class ServiceSend implements Runnable{
    Socket socket=null;
    OutputStream outputStream=null;
    byte[] bytes=new byte[1024];
    public ServiceSend(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {

            while (true) {
                outputStream = socket.getOutputStream();
                System.out.println("服务端发送线程开始工作");
                BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in));
                String str=bufferedReader.readLine();
                outputStream.write(str.getBytes());
                outputStream.flush();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

SendGroup

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;

public class SendGroup implements Runnable{
    ArrayList arrayList=null;
    Socket socket=null;
    byte[] bytes=null;
    Socket parentsocket=null;

    public SendGroup(Socket parentsocket,ArrayList arrayList, byte[] bytes) {
        this.arrayList = arrayList;
        this.bytes=bytes;
        this.parentsocket=parentsocket;
    }

    @Override
    public void run() {
        for (int i=0;i<arrayList.size();i++){
            socket= (Socket) arrayList.get(i);
            if (socket==parentsocket)
                continue;
            try {
                OutputStream outputStream = socket.getOutputStream();
                outputStream.write(bytes);
                outputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}

MyClient

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

public class MyClient {
    public static void main(String[] args) {
      Socket socket=null;
      OutputStream outputStream=null;
        try {
            socket=new Socket("127.0.0.1",8888);
            new Thread(new ClientReceive(socket)).start();
            new Thread(new ClientSend(socket)).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

ClientSend

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

public class ClientSend implements Runnable {
    Socket socket = null;
    OutputStream outputStream = null;
    byte[] bytes = new byte[1024];

    public ClientSend(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            while (true) {
                outputStream = socket.getOutputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
                String str = bufferedReader.readLine();
                outputStream.write(str.getBytes());
                outputStream.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

ClientReceive


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

public class ClientReceive implements Runnable {
    Socket socket = null;
    InputStream inputStream = null;
    byte[] bytes = new byte[1024];
    String str;
    int length;

    public ClientReceive(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {



        try {
            while (true){
                System.out.println("客户端接受线程开始工作");
                inputStream =socket.getInputStream();
                length=inputStream.read(bytes);
                while (length!=-1){
                    System.out.println(new String(bytes));
                    length=inputStream.read(bytes);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}