通过套接字发送多个变量? [英] Sending multiple variables through a socket?

查看:97
本文介绍了通过套接字发送多个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始学习Java中的套接字网络.因此,我创建了可以在同一台计算机上玩的多人游戏,但是我想使其成为网络多人游戏,然后我了解了套接字,现在,我想将游戏中玩家位置的变量发送给然后,该服务器可以将该玩家放置在另一台计算机上运行的其他游戏实例中的该位置.事情是,我只是失败了,所有数据都没有被接收或读取.我也希望职位不断得到发送和接收,这对我来说也是个问题...

我尝试使用ObjectOutputStream和ObjectInputStream发送带有变量的int数组,但是也失败了,所以请您告诉我如何执行此操作,因为我不知道,而且我似乎无法在线找到答案.

Thx

解决方案

作为最简单的解决方案,使用对象流将您创建的对象发送到存储这些坐标的位置,但是此类必须实现Serializable接口.例如二维坐标:

class Coords implements Serializable {
    int x, y;
    public Coords(int x, int y) {
        this.x = x;
        this.y = y;
    }       
}

...

// To write:
// oos = ObjectOutputStream of the socket
Coords tmp = new Coords(x, y);
oos.writeObject(tmp);
oos.flush();

...

//To read:
//ois = ObjectInputStream of the socket
Coords tmp = (Coords)ois.readObject();

http://java.sun.com/developer/technicalArticles/ALT/sockets/也可以帮助您.

I recently started learning networking with sockets in java. So i've created a multiplayer game that is playable on the same computer but i wanted to make it network-multiplayer, then i learned about sockets, now, i want to send the variables of the position of the player in the game to a server which then can place that player in that position in the other game instance running on a different machine. And the thing is, i just fail at it and all the data doesnt get received or read. I also want the position to get sent and received constantly which is also a problem for me...

I tried using ObjectOutputStream and ObjectInputStream to send a int array with the variables but that also failed, so could you please show me how to do this, because i have no idea and i cant seem to find an answer online.

Thx

解决方案

As the easiest solution, use the Object Streams to send an object created by you where you store these coordinates, but this class must implement Serializable interface. For example for 2d coordinates:

class Coords implements Serializable {
    int x, y;
    public Coords(int x, int y) {
        this.x = x;
        this.y = y;
    }       
}

...

// To write:
// oos = ObjectOutputStream of the socket
Coords tmp = new Coords(x, y);
oos.writeObject(tmp);
oos.flush();

...

//To read:
//ois = ObjectInputStream of the socket
Coords tmp = (Coords)ois.readObject();

http://java.sun.com/developer/technicalArticles/ALT/sockets/ can also aid you.

这篇关于通过套接字发送多个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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