[英]WebSocket Server (Java) cannot read but send to C# (Unity) Client
对于大学的项目,我们应该建立一个多人游戏。 因为我在Unity中有很多经验我想用它作为游戏引擎。 我们必须使用WebSockets进行通信,使用json作为protocoll来传输数据。
到现在为止还挺好。 C#没有默认的websocket实现,所以我使用了一个名为websocket-sharp的库( https://github.com/sta/websocket-sharp )。
我在客户端(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);
}
}
我尝试使用托管echo服务器的在线服务实现我的实现( http://demos.kaazing.com/echo/ ),一切正常。
我用Java编写了一个基本的echo服务器,并使用浏览器插件( https://chrome.google.com/webstore/detail/simple-websocket-client/pfdhoblngboilpfeibdedpjgfnlcodoo )和上面的echo服务器网站检查服务器。 两者都像魅力一样。
来自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问题:
Unity客户端无法将数据发送到服务器! 他可以正常连接并可以从服务器读取消息,但他无法发送给他(触发onmesssage)。 我整天搜索都没有成功。
客户端在线服务也很好,服务器也很好,但是它们都不起作用。 有谁能解释一下? 我会爱你<3
问候Pascal
一天后,我发现了问题。
Websockets能够处理字符串,byte []和更多格式。
我发送了这样的数据:
public void SendString(string str)
{
Send (Encoding.UTF8.GetBytes (str));
}
并使用了底层的Send(byte [])方法。 所以当我将Java中的@OnMessage方法更改为
@OnMessage
public void processUpload(byte[] bytes, boolean last, Session session) {
一切正常,而且反过来我可以发送一个字符串,我的服务器也收到我的消息:)
也许对某些人来说,知道它是有用的
问候Pascal
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.