java java中客户端和服务器之间的通信方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6247907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to communicate between client and server in java
提问by KIRAN K J
I have a chat program. Now the code works for communicate between client and server via command line. But it gives an exception (java.net.SocketException: Socket is closed) while running. Please help me to fix that problem.
我有一个聊天程序。现在该代码可用于通过命令行在客户端和服务器之间进行通信。但是它在运行时给出了一个异常(java.net.SocketException: Socket is closed)。请帮我解决这个问题。
In a java chat program,how will the communication be implemented between client and server?
在java聊天程序中,客户端和服务器之间的通信是如何实现的?
ie.
IE。
client<-->server (between server and client)
客户端<-->服务器(在服务器和客户端之间)
or
client A<-->server<-->client B (server act as a bridge between two clients)
客户端A<-->服务器<-->客户端B(服务器充当两个客户端之间的桥梁)
Is the 2 way communication can be implemented through a single socket? Are there any other methods ? How to communicate more than one client simultaneously?
是否可以通过单个套接字实现 2 路通信?还有其他方法吗?如何同时与多个客户端通信?
server code
服务器代码
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);
}
}
}
client code
客户代码
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);
}
}
}
采纳答案by Stuti
First of all, don't close the streams in every run().
首先,不要在每次 run() 中关闭流。
Secondly, check whether port for server which you are using is free.
其次,检查您使用的服务器的端口是否空闲。
回答by Suhail Gupta
This program makes your pc both host and server.
该程序使您的电脑既是主机又是服务器。
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();
}
}
}
also follow this link
也可以点击这个链接
回答by Vineet Reynolds
There could be multiple places where the exception could be thrown. Without a stack trace it is difficult to state so accurately, as to the cause of failure.
可能有多个地方可以抛出异常。如果没有堆栈跟踪,就很难如此准确地说明失败的原因。
But the root cause, is essentially due to the fact that you are closing the InputStream of the socket in your Receiver threads after reading a message, and closing the OutputStream of the socket in your Sender threads after sending a message. Closing either of these streams will automatically close the socket, so you if attempt to perform any further operation on it, a SocketException will be thrown.
但根本原因,本质上是因为您在读取消息后在接收器线程中关闭了套接字的 InputStream,并在发送消息后在发送器线程中关闭了套接字的 OutputStream。关闭这些流中的任何一个都将自动关闭套接字,因此如果您尝试对其执行任何进一步的操作,将抛出 SocketException。
If you need to ensure that your server and client do not shutdown in such an abrupt manner, you'll have to keep reading the InputStream (until you get a special message to shutdown, for instance). At the same time, you'll also have to keep writing to the OutputStream. Two-way communication is definitely possible, and the posted code is capable of the same (if the socket remains open).
如果您需要确保您的服务器和客户端不会以如此突然的方式关闭,您将不得不继续阅读 InputStream(例如,直到您收到一条特殊的关闭消息)。同时,您还必须继续写入 OutputStream。双向通信绝对是可能的,并且发布的代码具有相同的功能(如果套接字保持打开状态)。
If you have to handle multiple clients, you'll need multiple reader and writer threads on the server, each listening on an instance of a Socket returned from ServerSocket.accept()
; in simpler words, you need a reader-writer pair listening on a distinct socket on the server for each client. At the moment, multiple clients can connect to the Server, as each incoming connection is provided its own client Socket object on the Server, that is provided to individual reader and writer threads. The main Server thread can continue to receive incoming connections and delegate the actual work to the reader-writer pairs.
如果您必须处理多个客户端,则服务器上需要多个读取器和写入器线程,每个线程都侦听从ServerSocket.accept()
;返回的 Socket 实例;简而言之,您需要一个读写器对,为每个客户端侦听服务器上的不同套接字。目前,多个客户端可以连接到服务器,因为每个传入连接都在服务器上提供了自己的客户端 Socket 对象,该对象提供给单独的读取器和写入器线程。主服务器线程可以继续接收传入连接并将实际工作委托给读写器对。
回答by Jens Schauder
chat programms normaly have a server through which all communication goes. The reason is that other wise every client needs to know how to reach every other client. And that doesn't work in the general case.
聊天程序通常有一个服务器,所有通信都通过它进行。原因是其他明智的每个客户都需要知道如何联系其他每个客户。这在一般情况下不起作用。
So you'll have a server, every client registers and talks with the server, which will forward messages to other clients.
所以你会有一个服务器,每个客户端都注册并与服务器对话,服务器将消息转发给其他客户端。
Mostly communication is done via HTTP cause this is likely to go through firewalls and proxies. You probably want to read up on long polling if you are planning for anything serious.
大多数通信是通过 HTTP 完成的,因为这可能会通过防火墙和代理。如果您正在计划任何严肃的事情,您可能想要阅读长轮询。