I am attempting to create a web socket server using typescript and integrate it with Unity (client). However, I am encountering a string conversion error when trying to communicate with Unity. Interestingly, my friends used the same socket server code in their Unity projects without any errors. Curiously, when I tested my client code with another project, the same error persisted. Although I use Korean as my computer language, there are no Korean characters in my project directory.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net.WebSockets;
using System;
using System.Threading;
public class SocketManager : MonoBehaviour
{
private ClientWebSocket _socket = null;
private void Start()
{
Connection();
}
public async void Connection()
{
Debug.Log("Starting Connection");
if (_socket != null && _socket.State == WebSocketState.Open)
{
Debug.Log("Socket already connected");
return;
}
_socket = new ClientWebSocket();
Uri serverUri = new Uri("ws://localhost:50000");
await _socket.ConnectAsync(serverUri, CancellationToken.None);
Debug.Log("Connected");
ArraySegment<byte> bufferSegment = new ArraySegment<byte>(new byte[1024]);
WebSocketReceiveResult result = await _socket.ReceiveAsync(bufferSegment, CancellationToken.None);
string msg = System.Text.Encoding.UTF8.GetString(bufferSegment.Array);
Debug.Log(msg);
}
private void OnDestroy()
{
Disconnect();
}
public void Disconnect()
{
if (_socket != null)
{
_socket.CloseAsync(WebSocketCloseStatus.NormalClosure,
"Quit",
CancellationToken.None);
}
}
}
My WS server code:
import Express, { Application } from 'express';
import {IncomingMessage} from 'http'
import WS from 'ws';
const App: Application = Express();
const httpServer = App.listen(50000, () =>{
console.log("Server is running on 50000 port");
});
const socketServer : WS.Server = new WS.Server({
server:httpServer,
//port:9090
}, () => {
console.log("Socket server is running on 50000 port");
});
socketServer.on("connection", (soc:WS, req:IncomingMessage) => {
payload: Uint8Array = new Uint8Array(20);
soc.send("Welcome to My Server!");
});
The Error
ExecutionEngineException: String conversion error: Illegal byte sequence encounted in the input. System.Net.Dns.GetHostByName (System.String hostName) (at :0) System.Net.Dns.GetHostEntry (System.String hostNameOrAddress) (at :0) System.Net.Dns.GetHostAddresses (System.String hostNameOrAddress) (at :0) (wrapper delegate-end-invoke) .end_invoke_IPAddress[]__this___IAsyncResult(System.IAsyncResult) System.Net.Dns.EndGetHostAddresses (System.IAsyncResult asyncResult) (at :0) System.Threading.Tasks.TaskFactory`1[TResult].FromAsyncCoreLogic (System.IAsyncResult iar, System.Func`2[T,TResult] endFunction, System.Action`1[T] endAction, System.Threading.Tasks.Task`1[TResult] promise, System.Boolean requiresSynchronization) (at :0) End of stack trace from previous location where exception was thrown ---