java 多客户端聊天不发送和接收消息

w46czmvw  于 2023-06-20  发布在  Java
关注(0)|答案(1)|浏览(135)

我试图开发一个多客户端聊天应用程序使用java套接字编程。我用的是下面的代码
我使用的是从互联网上截取的下面的代码,并做了一些修改
Srever.java

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    
    
    private final ServerSocket serversocket;
    
    
    public Server (ServerSocket serversocket)
    {
        this.serversocket = serversocket;
    }
    
    
    public void startserver ()
    {
        try
        {
            while (!serversocket.isClosed())
            {
                Socket socket = serversocket.accept();
                System.out.println("A client is connected");
                
                ClientHandler clienthandler = new ClientHandler(socket);
                Thread t = new Thread(clienthandler);
                t.start();
                
                
            }
        }catch (IOException e)
        {
            
        }
    }
    
   
    public static void main(String[] args) throws IOException 
    {
       ServerSocket serversocket = new ServerSocket(5000);
       Server server = new Server(serversocket);
       server.startserver();
        
    }
}

ClientHandler.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;

public class ClientHandler  implements Runnable
{
    public static ArrayList <ClientHandler>clienthandlers = new ArrayList<>() ;
    private final Socket socket;
    private final BufferedReader bufferedreader;
    private final PrintWriter writer; 
    private final String clientusername;
    
    public ClientHandler(Socket socket) throws IOException
    {
        this.socket = socket;
        bufferedreader =  new BufferedReader(new InputStreamReader(socket.getInputStream()));
        writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),true);
        clientusername = bufferedreader.readLine().trim();
        
   
    }
    
    
    @Override
    public void run ()
    {
   
    try {
        
        System.out.println(clientusername+ " has joined the achat");
        clienthandlers.add(this);
        broadcastMessage ("SERVER :" + clientusername+ " has joined the chat");
        
        
        while (socket.isConnected())
        {
            String messageFromClient; 
            messageFromClient= bufferedreader.readLine();
            broadcastMessage(messageFromClient);
            }
        }catch (IOException e)
            {
                closeEverything(socket,bufferedreader,writer) ;
               
            }
        
    }
    
 public void broadcastMessage (String messageToSend)
 {
     
     for (ClientHandler ch: clienthandlers)
     {
         if (!ch.clientusername.equals(clientusername)) 
         {
             ch.writer.println(messageToSend);
 
         }
     }
     
 }
 
 
 public void removeClientHandler ()
 {
     clienthandlers.remove(this);
     System.out.println(clientusername+ " has left the achat");
     broadcastMessage ("SERVER :" + clientusername+ " has left the achat");
 }

    private void closeEverything(Socket socket, BufferedReader bufferedreader, PrintWriter writeer)
    {
        removeClientHandler();
       try 
        {
           if (bufferedreader!=null)
           {
            bufferedreader.close();
           }
        
           if (writeer!=null)
           {
            writeer.close();
           }
        
           if (socket!=null)
           {
            socket.close();
           }
        }catch (IOException e)
        {
        }
        
    }
 
}

Client.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    
 private Socket socket;
 private BufferedReader bufferedreader;
 private PrintWriter writer; 
 private String username; 
 
 
 public Client (Socket socket, String username)
 {
       try
       {
        this.socket = socket;
        this.bufferedreader =  new BufferedReader(new InputStreamReader(socket.getInputStream()));
        this.writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),true);
        this.username = username;
        writer.println(username);
       }catch (IOException e)
       {
           closeEverything(socket, bufferedreader, writer);
       }
 }
    
 private void sendMessage ()
 {
     
     Scanner sc = new Scanner(System.in);
     while (socket.isConnected())
     {
         String messageToSend = sc.nextLine();
         writer.write(username+ ": " + messageToSend);
         
     }
 }
 
 
 
 public void listenForMessage ()
 {
     new Thread(() -> {
         String messageFromGroupchat;
         
         while (socket.isConnected()) 
         {
             try
             {
                 messageFromGroupchat = bufferedreader.readLine();
                 System.out.println(messageFromGroupchat);
             }catch (IOException e)
             {
                 closeEverything(socket, bufferedreader, writer);
             }
         }
     }).start();
 }
 
 
 
 
 private void closeEverything(Socket socket, BufferedReader bufferedreader, PrintWriter writeer)
    {
                
        try 
        {
           if (bufferedreader!=null)
           {
            bufferedreader.close();
           }
        
           if (writeer!=null)
           {
            writeer.close();
           }
        
           if (socket!=null)
           {
            socket.close();
           }
        }catch (IOException e)
        {
        }
        
    } 
 
 
    public static void main(String[] args) throws IOException 
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter your name");
        String username = sc.nextLine();
        
        Socket socket = new Socket("localhost", 5000);
        
        Client client = new Client(socket, username);
       
        client.listenForMessage();
        
        client.sendMessage();
       
       
       
       
    }
}

问题是当客户端连接时,它们之间没有消息(发送/接收)。他们只是在加入或离开聊天时才通知对方。我到底犯了什么错?我是socket编程的新手。

zyfwsgd6

zyfwsgd61#

请注意区别,当您发送使用“writer.println”的名称时,当您发送使用“writer.write”的消息时
什么时候发送一个新的行字符?
在客户端将其更改为“println”,或者在消息末尾发送“\n”。
另一件事是,客户端处理程序中的while (socket.isConnected())将无法工作。根据isConnected文档,您应该使用isClosed()

相关问题