關鍵點:發送端與接收端統一使用 Unicode 編碼。
try {
IPAddress MyIP = IPAddress.Parse("127.0.0.1");
TcpListener MyListener = new TcpListener(MyIP, 1235);
MyListener.Start();
Socket MySocket = MyListener.AcceptSocket();
byte[] MyData = new byte[256];
MySocket.Receive(MyData);
// 接收時用 Unicode 解碼
this.richTextBox1.AppendText(System.Text.Encoding.Unicode.GetString(MyData));
// 發送時用 Unicode 編碼
UnicodeEncoding MyInfo = new UnicodeEncoding();
MySocket.Send(MyInfo.GetBytes("From Server:你好!我是服務器"));
} catch (Exception ex) {
MessageBox.Show(ex.Message, "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
try {
TcpClient MyClient = new TcpClient();
MyClient.Connect("127.0.0.1", 1235);
Stream MyStream = MyClient.GetStream();
UnicodeEncoding MyInfo = new UnicodeEncoding();
byte[] MyData = new byte[256];
byte[] MySendByte = MyInfo.GetBytes("From Client:你好!我是客戶端");
MyStream.Write(MySendByte, 0, MySendByte.Length);
MyStream.Read(MyData, 0, 256);
this.richTextBox1.AppendText(System.Text.Encoding.Unicode.GetString(MyData));
} catch (Exception ex) {
MessageBox.Show(ex.Message, "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
關鍵點:參數前綴 N + 欄位型別用 N 系列。
-- 建表時 CREATE TABLE T ( col1 NVARCHAR(100), -- N 系列支援 Unicode col2 NTEXT ); -- 參數化查詢(推薦) INSERT INTO T VALUES (N'中文內容', N'更多中文'); -- 字串拼接時(不推薦,防注入) string sql = "INSERT INTO T VALUES (N'" + value1 + "', N'" + value2 + "')";
| 層面 | SQL Server | MySQL |
|---|---|---|
| 字元集 | UTF-16 (NVARCHAR) | utf8mb4 (CHARSET=utf8mb4) |
| 連線設定 | 自動協商 | SET NAMES utf8mb4 或連接字串 CharSet=utf8mb4 |
| 參數化 | SqlParameter | MySqlParameter |
| C# 字串 | 原生 Unicode | 原生 Unicode,驅動自動轉換 |