Unity与TypeScript WebSocket通信时出现字符串转换错误
问题背景
用TypeScript搭建WebSocket服务器对接Unity客户端时,出现字符串转换错误。朋友使用我的服务器代码在Unity中运行无异常,但我将自己的客户端代码放到其他项目中仍会触发相同错误。系统语言为韩语,但项目目录内未发现韩语内容。
Unity客户端C#代码
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); } } }
TypeScript WebSocket服务器代码
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!"); });
错误信息
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.TaskFactory1[TResult].FromAsyncCoreLogic (System.IAsyncResult iar, System.Func2[T,TResult] endFunction, System.Action1[T] endAction, System.Threading.Tasks.Task1[TResult] promise, System.Boolean requiresSynchronization) (at :0)
End of stack trace from previous location where exception was thrown ---
排查与解决方法
1. 绕开DNS解析
错误栈显示问题出在DNS解析阶段,和韩语系统的编码设置冲突。直接使用IP地址替代localhost:
Uri serverUri = new Uri("ws://127.0.0.1:50000");
同时检查系统hosts文件,确保localhost指向127.0.0.1,且文件内无韩语或非ASCII字符。
2. 修正字符串解码逻辑
当前解码时使用整个buffer数组,包含未使用的空字节,易引发编码错误。仅解码实际接收的字节长度:
string msg = System.Text.Encoding.UTF8.GetString(bufferSegment.Array, 0, result.Count);
3. 修复服务器代码语法错误
服务器代码存在未声明变量的语法问题,虽未实际使用,但可能影响稳定性:
// 原错误代码 // payload: Uint8Array = new Uint8Array(20); // 修正后 const payload: Uint8Array = new Uint8Array(20);
4. 调整Unity与系统编码设置
- 在Unity中打开
Edit > Project Settings > Player,将Other Settings里的Scripting Runtime Version设为.NET 4.x Equivalent,提升编码兼容性。 - 调整系统区域语言设置,将非Unicode程序的语言设为英语(美国),避免编码转换冲突。
内容的提问来源于stack exchange,提问作者Minjoon Park

