简体   繁体   中英

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. We have to use WebSockets for communication and json as protocoll to carry the data.

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 ).

My Code on client (Unity) side is as followed:

    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.

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. Both working like a charm.

Code from Java Server (running in 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:

The Unity client cannot send data to the server! He can connect properly and can read messages from the Server, but he cannot send him (trigger 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

Greetings Pascal

A day later I found the problem.

Websockets have the ability to handle string, byte[] and some more formats.

I sended my data like this:

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

And used the underlying Send(byte[]) method. So when I change the @OnMessage method in Java to

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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