从 Socket.ReceiveFrom() 收到的数据不正确
Incorrect data received from Socket.ReceiveFrom()
我有一个 UDP 服务器。对于测试,我有一个测试方法 TryMe()
,它在我的 UDP 服务器上发送 1:2:Test Device
。
当我试图获取接收到的数据时,它 returns 㨱㨲敔瑳搠癥捩�
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace MidiRouter
{
class Server
{
string serverAddress = "127.0.0.1";
int serverPort = 3005;
bool isRunning = false;
Socket listeningSocket;
public delegate void OnMessageCallback(string remoteAddress, int remotePort, int note, int velocity, string deviceName);
public OnMessageCallback OnNewMessage;
public delegate void OnMessageErrorCallback(Exception ex);
public OnMessageErrorCallback OnMessageError;
public delegate void OnServerRuntimeErrorCallback(Exception ex);
public OnServerRuntimeErrorCallback OnServerRuntimeError;
static Server instance;
public string ServerAddress
{
get
{
return serverAddress;
}
set
{
if (!isRunning)
{
serverAddress = value;
}
}
}
public int ServerPort
{
get
{
return serverPort;
}
set
{
if (!isRunning)
{
serverPort = value;
}
}
}
public Server()
{
instance = this;
OnNewMessage = noCallBack;
OnMessageError = noMsgErrors;
OnServerRuntimeError = noSrvRuntimeErrors;
}
void noCallBack(string remoteAddress, int remotePort, int note, int velocity, string deviceName)
{
}
void noMsgErrors(Exception e)
{
}
void noSrvRuntimeErrors(Exception e)
{
}
public bool IsRunning()
{
return isRunning;
}
public void Start()
{
try
{
listeningSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
Task listeningTask = new Task(Listen);
listeningTask.Start();
}
catch (Exception ex)
{
throw ex;
}
isRunning = true;
}
public void TryMe()
{
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
IPAddress serverAddr = IPAddress.Parse(serverAddress);
IPEndPoint endPoint = new IPEndPoint(serverAddr, serverPort);
string text = "1:2:Test device";
byte[] send_buffer = Encoding.ASCII.GetBytes(text);
sock.SendTo(send_buffer, endPoint);
}
static void Listen()
{
Server me = instance;
try
{
//Прослушиваем по адресу
IPEndPoint localIP = new IPEndPoint(IPAddress.Parse(me.serverAddress), me.serverPort);
me.listeningSocket.Bind(localIP);
int note, velocity;
while (true)
{
// получаем сообщение
StringBuilder builder = new StringBuilder();
int bytes = 0; // количество полученных байтов
byte[] data = new byte[256]; // буфер для получаемых данных
//адрес, с которого пришли данные
EndPoint remoteIp = new IPEndPoint(IPAddress.Any, 0);
do
{
bytes = me.listeningSocket.ReceiveFrom(data, ref remoteIp);
builder.Append(Encoding.Unicode.GetString(data, 0, bytes));
}
while (me.listeningSocket.Available > 0);
// получаем данные о подключении
IPEndPoint remoteFullIp = remoteIp as IPEndPoint;
string fullData = builder.ToString();
System.IO.File.WriteAllText("D:\test.txt", System.IO.File.ReadAllText("D:\test.txt") + "\n" + fullData);
string[] fullDataSplitted = fullData.Split(':');
if (fullDataSplitted.Length < 3)
{
continue;
}
List<string> deviceNameSplitted = new List<string>();
string deviceName;
try
{
note = Convert.ToInt32(fullDataSplitted[0]);
}
catch (Exception ex)
{
me.OnMessageError(ex);
continue;
}
try
{
velocity = Convert.ToInt32(fullDataSplitted[1]);
}
catch (Exception ex)
{
me.OnMessageError(ex);
continue;
}
for (int i = 2; i < fullDataSplitted.Length; i++)
{
deviceNameSplitted.Add(fullDataSplitted[i]);
}
deviceName = String.Join(" ", deviceNameSplitted.ToArray());
me.OnNewMessage(remoteFullIp.Address.ToString(), remoteFullIp.Port, note, velocity, deviceName);
}
}
catch (Exception ex)
{
if (me.isRunning)
{
try
{
me.Close();
}
catch (Exception ex1)
{
}
me.OnServerRuntimeError(ex);
}
}
}
public void Close()
{
isRunning = false;
if (listeningSocket != null)
{
listeningSocket.Shutdown(SocketShutdown.Both);
listeningSocket.Close();
listeningSocket = null;
}
}
}
}
您的问题出在这一行:
byte[] send_buffer = Encoding.ASCII.GetBytes(text);
应该使用UTF8
byte[] send_buffer = Encoding.UTF8.GetBytes(text);
我有一个 UDP 服务器。对于测试,我有一个测试方法 TryMe()
,它在我的 UDP 服务器上发送 1:2:Test Device
。
当我试图获取接收到的数据时,它 returns 㨱㨲敔瑳搠癥捩�
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace MidiRouter
{
class Server
{
string serverAddress = "127.0.0.1";
int serverPort = 3005;
bool isRunning = false;
Socket listeningSocket;
public delegate void OnMessageCallback(string remoteAddress, int remotePort, int note, int velocity, string deviceName);
public OnMessageCallback OnNewMessage;
public delegate void OnMessageErrorCallback(Exception ex);
public OnMessageErrorCallback OnMessageError;
public delegate void OnServerRuntimeErrorCallback(Exception ex);
public OnServerRuntimeErrorCallback OnServerRuntimeError;
static Server instance;
public string ServerAddress
{
get
{
return serverAddress;
}
set
{
if (!isRunning)
{
serverAddress = value;
}
}
}
public int ServerPort
{
get
{
return serverPort;
}
set
{
if (!isRunning)
{
serverPort = value;
}
}
}
public Server()
{
instance = this;
OnNewMessage = noCallBack;
OnMessageError = noMsgErrors;
OnServerRuntimeError = noSrvRuntimeErrors;
}
void noCallBack(string remoteAddress, int remotePort, int note, int velocity, string deviceName)
{
}
void noMsgErrors(Exception e)
{
}
void noSrvRuntimeErrors(Exception e)
{
}
public bool IsRunning()
{
return isRunning;
}
public void Start()
{
try
{
listeningSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
Task listeningTask = new Task(Listen);
listeningTask.Start();
}
catch (Exception ex)
{
throw ex;
}
isRunning = true;
}
public void TryMe()
{
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
IPAddress serverAddr = IPAddress.Parse(serverAddress);
IPEndPoint endPoint = new IPEndPoint(serverAddr, serverPort);
string text = "1:2:Test device";
byte[] send_buffer = Encoding.ASCII.GetBytes(text);
sock.SendTo(send_buffer, endPoint);
}
static void Listen()
{
Server me = instance;
try
{
//Прослушиваем по адресу
IPEndPoint localIP = new IPEndPoint(IPAddress.Parse(me.serverAddress), me.serverPort);
me.listeningSocket.Bind(localIP);
int note, velocity;
while (true)
{
// получаем сообщение
StringBuilder builder = new StringBuilder();
int bytes = 0; // количество полученных байтов
byte[] data = new byte[256]; // буфер для получаемых данных
//адрес, с которого пришли данные
EndPoint remoteIp = new IPEndPoint(IPAddress.Any, 0);
do
{
bytes = me.listeningSocket.ReceiveFrom(data, ref remoteIp);
builder.Append(Encoding.Unicode.GetString(data, 0, bytes));
}
while (me.listeningSocket.Available > 0);
// получаем данные о подключении
IPEndPoint remoteFullIp = remoteIp as IPEndPoint;
string fullData = builder.ToString();
System.IO.File.WriteAllText("D:\test.txt", System.IO.File.ReadAllText("D:\test.txt") + "\n" + fullData);
string[] fullDataSplitted = fullData.Split(':');
if (fullDataSplitted.Length < 3)
{
continue;
}
List<string> deviceNameSplitted = new List<string>();
string deviceName;
try
{
note = Convert.ToInt32(fullDataSplitted[0]);
}
catch (Exception ex)
{
me.OnMessageError(ex);
continue;
}
try
{
velocity = Convert.ToInt32(fullDataSplitted[1]);
}
catch (Exception ex)
{
me.OnMessageError(ex);
continue;
}
for (int i = 2; i < fullDataSplitted.Length; i++)
{
deviceNameSplitted.Add(fullDataSplitted[i]);
}
deviceName = String.Join(" ", deviceNameSplitted.ToArray());
me.OnNewMessage(remoteFullIp.Address.ToString(), remoteFullIp.Port, note, velocity, deviceName);
}
}
catch (Exception ex)
{
if (me.isRunning)
{
try
{
me.Close();
}
catch (Exception ex1)
{
}
me.OnServerRuntimeError(ex);
}
}
}
public void Close()
{
isRunning = false;
if (listeningSocket != null)
{
listeningSocket.Shutdown(SocketShutdown.Both);
listeningSocket.Close();
listeningSocket = null;
}
}
}
}
您的问题出在这一行:
byte[] send_buffer = Encoding.ASCII.GetBytes(text);
应该使用UTF8
byte[] send_buffer = Encoding.UTF8.GetBytes(text);