所以我有一个客户端,我无法访问源代码,客户端是超级基本的,但它连接到我的服务器,发送一个类似于A8745783-K8757853
的字符串给我的客户端
然后我的代码收到它:
如何将其存储为看起来像这样的字符串A8745783-K8757853
我希望收到的信息值为A8745783-K8757853
而不是A/06/05/02/06..
我不确定为什么我的服务器会像那样存储它,这就是我想知道的,我如何正确地接收缓冲区作为字符串?
public class Connection
{
private const int Port = 12345;
public static List<string[]> CardList = new List<string[]>();
public static List<string[]> UserList = new List<string[]>();
public static List<string[]> ReceivedList = new List<string[]>();
//Make them private because we don't want to mess with these, it's "almost" like having them in a const form.. Keyword "Almost".
private static readonly IPAddress Ip = IPAddress.Parse("127.0.0.1");
private static TcpListener _listener;
private static TcpClient _client;
private static NetworkStream _nwStream;
public static int BytesAmount;
public static byte[] Buffer;
public Connection()
{
_listener = new TcpListener(Ip, Port);
}
public static string User { get; set; }
public static string Card { get; set; }
public static string UserData { get; set; }
public static string Received { get; set; }
public async Task StartListenAsync()
{
_listener.Start();
// This will sit in idle, waiting for a connection..
Console.WriteLine("Listening..");
// Assign the first connection to the client obj, we're doing this async.
_client = await _listener.AcceptTcpClientAsync();
_nwStream = _client.GetStream();
if (_client.Connected)
Console.WriteLine("Client has connected!");
// Keep listening for incoming data and split it.
while (true)
if (_nwStream.DataAvailable)
{
//long i = _nwStream.Length;
//Console.WriteLine(i);
Buffer = new byte[_client.ReceiveBufferSize];
BytesAmount = _nwStream.Read(Buffer, 0, _client.ReceiveBufferSize);
Received = Encoding.UTF8.GetString(Buffer, 0, BytesAmount);
string something = Received;
// Our IDE (Visual Studio (VS) knows to make this into a string array because we're calling split on a string
// So to not make it redundant we'll be fine by doing new[] which in this case represents a new string array)
var splitArray = Received.Split(new[] { "-" }, StringSplitOptions.None);
User = splitArray[0].Replace(" ", "");
Card = splitArray[1].Replace(" ", "");
Console.WriteLine("Testing 1: " + User);
Console.WriteLine("Testing 2: " + Card);
Console.WriteLine("Received: " + Received);
Console.WriteLine("Sending back : " + Received);
_nwStream.Write(Buffer, 0, BytesAmount);
}
}
}
答案 0 :(得分:0)
所以问题在于编码,我使用
Unicode
Recieved = Encoding.Unicode.GetString(Buffer, 0, BytesAmount);
而不是UTF8