两种连接方式
我正在制作一个java程序&我希望它既作为服务器又作为客户端(使用套接字)。如何最好地实现这一目标?
I'm making a java program & I want this to be both as server and a client (using sockets). How is this best achieved?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您的意思是既要发送又接收数据,则单个常规套接字(在每台计算机上)就可以了。请参阅 Socket.getInputStream 和 Socket.getOutputStream 。
通常的“服务器”/“客户端”区别只是归结为哪个主机正在侦听传入连接,以及哪些主机连接到这些主机。连接建立后,您就可以从两端发送和接收。
如果您希望两台主机都侦听传入连接,则只需在两台主机上设置
ServerSocket
并调用accept
即可。相关链接:
If you mean that you want to both send and receive data, a single regular socket (on each computer) will do just fine. See
Socket.getInputStream
andSocket.getOutputStream
.The usual "server" / "client" distinction just boils down which host is listening for incoming connections, and which hosts connect to those hosts. Once the connection is setup, you can both send and receive from both ends.
If you want both hosts to listen for incoming connections, then just set up a
ServerSocket
and callaccept
on both hosts.Related links:
如果你希望每个站都充当服务器和客户端,就像 p2p 聊天一样,
你应该使用 ServerSocket 实现一个线程,侦听传入的连接,一旦获得连接,就打开一个新线程来处理它,以便当前人们将继续监听新的连接。
为了能够连接到其他人,只需使用 SocketAddress 和 Socket,在不同的线程中尝试连接到指定的服务器地址(例如通过用户的朋友列表),
您可以通过谷歌搜索找到大量聊天示例。
干杯。
If you want each station to function as a server and a client, like a p2p chat,
you should implement a thread with a ServerSocket, listening for incoming connections, and once it got a connection, open a new thread to handle it so the current one will keep on listening for new connections.
For it to be able to connect to others, simple use SocketAddress and Socket, in a different thread to try to connect to a specified server address (e.g. by a list of the user's friends)
you can find plenty of chat examples by googling.
cheers.
如果您希望程序执行相同的操作,无论它是某个连接的服务器还是客户端,我可以想象同时关闭客户端 Socket 和 ServerSocket.accept( )-产生的socket以同样的方法进行处理。
If you want the program to perform the same operations regardless of whether it is a server or a client for a certain connection, I could imagine handing off both the client
Socket
and theServerSocket.accept()
-produced socket to the same method for processing.看看jgroups,它是一个库,允许创建进程组,其成员可以互相发送消息。另一种选择是使用 hazelcast ...
您也可以查看 这个问题。
Have a look at jgroups it's a library that allows the creation of groups of processes whose members can send messages to each other. Another option would be to use hazelcast...
You may also look at this question.
最好的方法是在一个线程上运行服务器:
您运行
server.accept()
因此,当您的程序在该线程上侦听连接时,您可以在主线程上执行任何您想要的操作线程,甚至连接到另一个服务器,因此使程序既是服务器又是服务器。一个客户。The best way to do this is to run the server on a thread:
You run
server.accept()
therefore while your program is listening for a connection on that thread you can do whatever you want on the main thread, even connect to another server therefore making the program both a server & a client.