Java多线程服务器 [英] Java multithreaded server

查看:267
本文介绍了Java多线程服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Java编写游戏服务器。在游戏服务器中很常见,我必须接收一个客户端收到的数据并将其分发到客户端的房间(其他客户端)。目前,每个客户端都会生成自己的线程并在其上工作。但是,我很难定义球员之间的关系。如何控制聊天等内容,哪些消息必须与同一房间内的所有其他玩家进行回音?我在考虑像消息队列这样的东西,所有线程都经常查找消息并将它们发送到自己的客户端。

I'm writing a game server in Java. As common in game servers, I must take data received by one client and distribute it over the client's room (other clients). Currently, each client spawns its own thread and works on top of that. I'm having trouble, however, to define the inter-player relations. How do I control something like chat, where a message must be echo'ed to all the other players in the same room? I'm thinking in something like a message queue, where all threads would often look for messages and send them to its own client.

我也愿意接受这样的建议:会立即抛弃多线程,但我不熟悉NIO,服务器已经使用普通的套接字线程 s。

I'm also open to suggestions that would ditch multithreading at once, but I'm not familiar with NIO and the server is already written using plain Sockets and Threads.

摘要:如何让我的客户(在线程中)互相交谈?或者是否有更好的非线程替代方案?

Summary: How do I make my clients (in threads) talk to each other? Or is there a better non-threaded alternative to this?

推荐答案

我提出的解决方案也类似于Jakeway。我已经以这种方式完全实现了相同的功能。

My proposed solution too is similar to Jakeway. I have exactly implemented the same feature in this way.


服务器将创建一个线程并在该线程中创建服务器套接字并等待连接

Server will create one thread and create Server Socket in that thread and waits for connection

客户端将连接到服务器。服务器将创建ClinetSocket并将此套接字传递给线程。此线程负责从服务器进行客户端/服务器通信

Client will connect to Server. Server will create ClinetSocket and pass this socket to thread. This thread is responsible for client/server communication from server

从客户端开始,在创建Socket时,将启动一个线程并且该线程负责客户端/服务器通信来自客户

Form the client side, on creation of Socket, one thread will start and that thread is responsible for client/server communication from client

从下面的链接查看一些现成的代码。

Have a look some of ready-made code from below links.

聊天示例1

聊天示例2

关于优点&使用套接字时,请访问以下链接: rmi vs servlets vs socket

Regarding Pros & Cons of socket usage, visit below link : rmi vs servlets vs sockets

关于客户之间的沟通?不可行。客户端将向服务器&发送消息。服务器应该向其他客户端发送消息。如果你看看雅虎的聊天情况

Regarding clients communication between them ? Not feasible. Client will send message to server & server should send message to other client. If you look at Yahoo kind of chat

1)你会在聊天室里向服务器发送消息

1) You will send message to server in a chat room

2)服务器有客户订阅客户端到聊天室的列表

2) Server have list of client subscribed clients to the chat room

3)服务器将向订阅房间的所有客户发送消息

3) Server will send message to all the clients subscribed to room

这篇关于Java多线程服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆