0

I am indeed new here, but I have been reading the responses for.. since I've began programming.

I am still new, and absolutely fresh out the womb when it comes to networking. But I'll keep this brief so you can give a conclusive answer.

I have a webserver and a domain name. I would like to use websockets to make an environment in which both players can move at the same time on the same screen. For example, if the mouse controlled a dot, and two people connected to a global "world" then a single person could see the dot of the other person in real time. An example of something like this would be rumpetroll.com.

I don't expect to get a whole lot about how to design a game like RuneScape (although I think that the idea is almost the same). I just want some in-depth explanation of how to get this cool little interaction going.

Any links to how to program to sockets would be GREATLY appreciated, because all I can find on the internet is the concept. Nothing on the mechanics and what each command may do.

Anyway, thanks guys.

4

1 回答 1

1

您将需要一个服务器和一个客户端。我假设您了解 JavaScript,所以我将提供一个在双方都使用它的示例。

服务器

您将需要nodejs,按照网站上的说明安装它。

我将使用socket.io提供示例,因为您要求使用 websockets,但请记住,还有其他解决方案,例如Faye,值得一看。

将自己放在一个新文件夹中,运行npm install socket.io,这将下载服务器所需的代码;然后将此代码粘贴到名为server.js

var io = require('socket.io').listen(8000);

io.sockets.on('connection', function (socket) {
  socket.emit('new-connection', { message: 'we have a new user!' });
  socket.on('message-from-client', function (data) {
    console.log(JSON,stringify(data));
  });
});

通过键入启动服务器node server.js,您应该info - socket.io started在控制台中看到。

客户端

将此代码粘贴到名为的文件中index.html,然后使用您喜欢的 Web 浏览器打开它

<script src="http://localhost:8000/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost:8000');
  socket.on('new-connection', function (data) {
    alert(JSON.stringify(data));
    socket.emit('message-from-client', { message: 'hi' });
  });
</script>

一旦你导航到http://localhost:8000你会看到两件事:

  • 警告你
  • 启动服务器的控制台中的消息

每次您导航到该网址时都会发生这种情况,请尝试使用两个不同的浏览器或在隐身/私人浏览窗口中导航到该网址。每次您都应该看到警报和消息。

这是基本设置。从这里开始,您可以将事情复杂化,如果您将使用此解决方案,请考虑在 JSON 中传递数据,如我在示例中所示。

从这往哪儿走

如您所见,这真的很容易,如果您想显示一个点,它将为所有用户显示,将客户端鼠标移动绑定到一个函数,该函数将位置发送到服务器并将其广播给所有其他连接的用户(应该是类似socket.broadcast.emit的东西,但我不确定请查看文档),或者您可以简单地发送一个事件,例如updated-mouse-position它将绑定一个函数来处理图形部分。

希望这会有所帮助,如果您对基本配置有疑问/问题,请随时添加评论。

于 2013-08-09T01:35:07.290 回答