简体   繁体   English

WebSocket Server(Java)无法读取但发送到C#(Unity)客户端

[英]WebSocket Server (Java) cannot read but send to C# (Unity) Client

For a project in university we should build a multiplayer game. 对于大学的项目,我们应该建立一个多人游戏。 Cause I have quiet a lot experience in Unity I want to use it as Game Engine. 因为我在Unity中有很多经验我想用它作为游戏引擎。 We have to use WebSockets for communication and json as protocoll to carry the data. 我们必须使用WebSockets进行通信,使用json作为protocoll来传输数据。

So far so good. 到现在为止还挺好。 C# don´t have a default websocket implementation, so I use a library called websocket-sharp for that ( https://github.com/sta/websocket-sharp ). C#没有默认的websocket实现,所以我使用了一个名为websocket-sharp的库( https://github.com/sta/websocket-sharp )。

My Code on client (Unity) side is as followed: 我在客户端(Unity)端的代码如下:

    public class EchoTest : MonoBehaviour {

    public GameObject master;
    public string serveradress = "ws://";

    private WebSocket w = null;

    // Use this for initialization
    IEnumerator Start () {
        w = new WebSocket(new Uri(serveradress));
        yield return StartCoroutine(w.Connect());

        w.SendString ("Hello World from client");
        //w.SendString("Hi there");
        int i=0;
        while (true)
        {
            string reply = w.RecvString();
            if (reply != null)
            {
                master.GetComponent<Networker> ().onNetworkMessage (reply);
                //Debug.Log ("Received: "+reply);
                //w.SendString("Hi there"+reply);
            }
            if (w.error != null)
            {
                Debug.LogError ("Error: "+w.error);
                break;
            }
            w.SendString("helloworld");
            yield return 0;
        }
        w.Close();
    }

    public void sendString(string message){
        sendRaw(Encoding.UTF8.GetBytes (message));
    }

    public void sendRaw(byte[] send){
        w.Send (send);
    }
}

I tried my implementation with an online service that hosts an echo server ( http://demos.kaazing.com/echo/ ) , everything works fine. 我尝试使用托管echo服务器的在线服务实现我的实现( http://demos.kaazing.com/echo/ ),一切正常。

I wrote a basic echo server in Java and checked the server with a browser plugin ( https://chrome.google.com/webstore/detail/simple-websocket-client/pfdhoblngboilpfeibdedpjgfnlcodoo ) and the echo server website from above. 我用Java编写了一个基本的echo服务器,并使用浏览器插件( https://chrome.google.com/webstore/detail/simple-websocket-client/pfdhoblngboilpfeibdedpjgfnlcodoo )和上面的echo服务器网站检查服务器。 Both working like a charm. 两者都像魅力一样。

Code from Java Server (running in Tomcat 9): 来自Java Server的代码(在Tomcat 9中运行):

@ServerEndpoint(value = "/echo")
public class WSEchoS {


    private static final Logger LOGGER =
            Logger.getLogger(WSEchoS.class.getName());

    @OnOpen
    public void onOpen(Session session) {
        LOGGER.log(Level.INFO, "New connection with client: {0}",
                session.getId());
        try {
            session.getBasicRemote().sendText("Hello new Client x");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnMessage
    public String onMessage(String message, Session session) {
        LOGGER.log(Level.INFO, "New message from Client [{0}]: {1}",
                new Object[]{session.getId(), message});
        try {
            session.getBasicRemote().sendText("This is from the server " + message);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "Server received [" + message + "]";
    }

    @OnClose
    public void onClose(Session session) {
        LOGGER.log(Level.INFO, "Close connection for client: {0}",
                session.getId());
    }

    @OnError
    public void onError(Throwable exception, Session session) {
        LOGGER.log(Level.INFO, "Error for client: {0}", session.getId());
    }
}

Nooooowwwww the problem: Nooooowwwww问题:

The Unity client cannot send data to the server! Unity客户端无法将数据发送到服务器! He can connect properly and can read messages from the Server, but he cannot send him (trigger onmesssage). 他可以正常连接并可以从服务器读取消息,但他无法发送给他(触发onmesssage)。 I searched the whole day without success. 我整天搜索都没有成功。

The client is working great with online services, the server as well, but both of them together don´t work. 客户端在线服务也很好,服务器也很好,但是它们都不起作用。 Can anyone explain that? 有谁能解释一下? I would love you for that <3 我会爱你<3

Greetings Pascal 问候Pascal

A day later I found the problem. 一天后,我发现了问题。

Websockets have the ability to handle string, byte[] and some more formats. Websockets能够处理字符串,byte []和更多格式。

I sended my data like this: 我发送了这样的数据:

public void SendString(string str)
{
    Send (Encoding.UTF8.GetBytes (str));
}

And used the underlying Send(byte[]) method. 并使用了底层的Send(byte [])方法。 So when I change the @OnMessage method in Java to 所以当我将Java中的@OnMessage方法更改为

@OnMessage
public void processUpload(byte[] bytes, boolean last, Session session) {

everything works fine, and also the other way around I can send a string and my server is also getting my messages :) 一切正常,而且反过来我可以发送一个字符串,我的服务器也收到我的消息:)

Maybe for some people it´s usefull to know 也许对某些人来说,知道它是有用的

Greetings Pascal 问候Pascal

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM