【问题标题】:how to communicate between client and server in javajava中客户端和服务端如何通信
【发布时间】:2011-09-09 00:38:54
【问题描述】:

我有一个聊天程序。现在代码适用于通过命令行在客户端和服务器之间进行通信。但是它在运行时给出了一个异常(java.net.SocketException: Socket is closed)。请帮我解决这个问题。

在一个java聊天程序中,客户端和服务器之间的通信是如何实现的?

即。

客户端服务器(服务器和客户端之间)

             or

客户端A服务器客户端B(服务器充当两个客户端之间的桥梁)

是否可以通过单个套接字实现 2 路通信? 还有其他方法吗? 如何同时与多个客户端通信?

服务器代码

class Server
{
ServerSocket server;
Socket client;
public Server()
{
    try
    {
        server = new ServerSocket(2000);
        System.out.println("\tServer Started..........");
        while (true)
        {
            client = server.accept();
            Send objsend = new Send(client);
            Recive objrecive = new Recive(client);
            //client.close();
        }
    }
    catch (Exception e)
    {
        System.out.println("Exception4 " + e);
    }
}
    public static void main(String arg[])
    {
        new Server();
    }
}
class Recive implements Runnable
{
    Socket client;
    public Recive(Socket client1)
    {
        client=client1;
        Thread trsend=new Thread(this);
        trsend.start();
    }
    public void run()
    {
        ObjectInputStream ois;
        Message M=new Message();
        try
        {
            ois = new ObjectInputStream(client.getInputStream());
            M = (Message)ois.readObject();
            M.display();
            ois.close();
        }
        catch (Exception e)
        {
            System.out.println("Exception1 " + e);
        }
    }
}    
class Send implements Runnable
{
    Socket client;
    public Send(Socket client1)
    {
        client=client1;
        Thread trrecive=new Thread(this);
        trrecive.start();
    }
    public void run()
    {
        Message M=new Message();
        InputStreamReader isr=new InputStreamReader(System.in);
        BufferedReader br=new BufferedReader(isr);
        try
        {
            System.out.println("Me(server)");
            M.strmessage=br.readLine();
            ObjectOutputStream oos=new ObjectOutputStream(cli    ent.getOutputStream());
            oos.writeObject((Message)M);
            oos.flush();
            oos.close();
        }
        catch (Exception e)
        {
            System.out.println("Exception " + e);
        }
    }
}

客户端代码

class Client
{
public static void main(String arg[])
{
    try
    {

        Send objsend=new Send();
        Recive objrecive=new Recive();
    }
    catch(Exception e)
    {
        System.out.println("Exception "+e);
    }

}
}
class Send implements Runnable
{

public Send()
{
    Thread trsend=new Thread(this);
    trsend.start();
}
public void run()
{

    try
    {
        Message M=new Message();
        InputStreamReader isr=new InputStreamReader(System.in);
        BufferedReader br=new BufferedReader(isr);
        while(true)
        {
            System.out.println("Me(client)");
            M.strmessage=br.readLine();

            Socket client=new Socket("localhost",2000);
            ObjectOutputStream oos=new ObjectOutputStream(client.getOutputStream());
            oos.writeObject((Message)M);

            oos.flush();
            oos.close();
        }
    }
    catch(Exception e)
    {
        System.out.println("Exception "+e);
    }
}
}
class Recive implements Runnable
{
public Recive()
{
    Thread trrecive=new Thread(this);
    trrecive.start();
}
public void run()
{

    try
    {
        while(true)
        {
        Socket client=new Socket("localhost",2000);
        ObjectInputStream ois=new ObjectInputStream(client.getInputStream());
        Message CNE=(Message)ois.readObject();
        CNE.display();

        ois.close();
        }

    }
    catch(Exception e)
    {
        System.out.println("Exception "+e);
    }
}
}

【问题讨论】:

标签: java network-programming


【解决方案1】:

首先,不要在每次 run() 中关闭流。

其次,检查你正在使用的服务器的端口是否空闲。

【讨论】:

  • 对不起,我不知道如何查看端口是否空闲?如何找到合适的端口?
  • 现在我用 2 个客户端和一个服务器控制客户端创建了一个聊天程序。即客户端可以通过服务器聊天。但是我需要与两个以上的人聊天。那么该怎么做呢?
【解决方案2】:

这个程序让你的电脑既是主机又是服务器。

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

 public class ClientServer {
  static byte[] buffer = new byte[100];
   private static void runClient() throws IOException {
   byte buffer[] = new byte[100]; 
   InetAddress address = InetAddress.getLocalHost();
 DatagramSocket ds=new DatagramSocket();
 int pos = 0;

  while (pos<buffer.length) {
   int c = System.in.read();
   buffer[pos++]=(byte)c;
   if ((char)c =='\n') 
     break;

 }
 System.out.println("Sending " + pos + " bytes");
 ds.send(new DatagramPacket(buffer, pos, address, 3000));

}

 private static void runServer() throws IOException {

InetAddress address = InetAddress.getLocalHost();
DatagramSocket ds = new DatagramSocket(3000, address);
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
ds.receive(dp);
String s=new String(dp.getData(),0,dp.getLength());
System.out.print(s);

}

public static void main(String args[]) throws IOException {
    if (args.length == 1) {
     runClient();
   }  else {
       runServer();
      }
 }
}

也关注this link

【讨论】:

【解决方案3】:

可能会在多个地方引发异常。如果没有堆栈跟踪,就很难准确地说明失败的原因。

但根本原因,本质上是由于您在读取消息后关闭接收器线程中套接字的输入流,并在发送消息后关闭发送器线程中套接字的输出流。关闭这些流中的任何一个都会自动关闭套接字,因此如果您尝试对其执行任何进一步的操作,则会抛出 SocketException。

如果您需要确保您的服务器和客户端不会以如此突然的方式关闭,您将不得不继续阅读 InputStream(例如,直到您收到关闭的特殊消息)。同时,您还必须继续写入 OutputStream。双向通信绝对是可能的,并且发布的代码也能够实现(如果套接字保持打开)。

如果您必须处理多个客户端,则需要在服务器上设置多个读取器和写入器线程,每个线程都侦听从ServerSocket.accept() 返回的 Socket 实例;简而言之,您需要一对读写器在服务器上为每个客户端侦听不同的套接字。目前,多个客户端可以连接到服务器,因为每个传入连接都在服务器上提供了自己的客户端 Socket 对象,该对象提供给各个读取器和写入器线程。主服务器线程可以继续接收传入的连接并将实际工作委托给读写器对。

【讨论】:

  • 谢谢......你的意思是,不需要“client = server.accept();”在while循环中?。如果是这样,如何知道消息被接收了?
  • 我的错。 while 循环使多个客户端能够连接。我将编辑我的答案。
  • 所有运行方法中是否需要while循环?如果需要,如何在获取新消息的同时获取事件???
  • 您是指发送者和接收者吗?如果是这样,那么是的,并且一旦遇到流的结尾(对于 InputStream)或一旦您不再希望写入流(对于 OutputStream),您应该跳出循环。在当前场景中,总共只会发送 1 条消息,具体取决于谁先发送。
  • 现在我用 2 个客户端和一个服务器控制客户端创建了一个聊天程序。即客户端可以通过服务器聊天。但是我需要与两个以上的人聊天。那么该怎么做呢?
【解决方案4】:

聊天程序通常有一个服务器,所有通信都通过该服务器进行。原因是每个客户都需要知道如何联系其他客户。这在一般情况下不起作用。

因此您将拥有一个服务器,每个客户端都注册并与服务器对话,服务器会将消息转发给其他客户端。

大多数通信是通过 HTTP 完成的,因为这很可能会通过防火墙和代理。如果您打算做一些严肃的事情,您可能想阅读长轮询。

【讨论】:

  • 现在我用 2 个客户端和一个服务器控制客户端创建了一个聊天程序。即客户端可以通过服务器聊天。但我需要与两个以上的人聊天。那么该怎么做呢?
猜你喜欢
  • 1970-01-01
  • 2015-05-08
  • 1970-01-01
  • 1970-01-01
  • 2012-04-21
  • 2016-02-12
  • 1970-01-01
  • 2016-05-05
  • 1970-01-01
相关资源
最近更新 更多