如何使用C#从客户端接收数据和套接字程序中的字符 [英] how to receive the data from Client in both numbers and Character in Socket program using C#

查看:82
本文介绍了如何使用C#从客户端接收数据和套接字程序中的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是Sever Code现在我想从客户端接收数字和字符串值的数据。我想在应用程序中接收两种方式。

接收字符串值但不是以数字值





This is the Sever Code Now i would like to receive data from the client in both numbers and string value.I want to receive both ways in the application.
am receiving in string value but not in numeric values


 TcpListener server = new TcpListener(IPAddress.Any, Port);
Console.Write("Waiting for Client connection... ");

 TcpClient client = server.AcceptTcpClient();
 Console.WriteLine("\nClient Connected....!");

NetworkStream stream = client.GetStream();

byte[] buffer = new byte[client.ReceiveBufferSize];
 int data = stream.Read(buffer, 0, client.ReceiveBufferSize);
 string ch = Encoding.Unicode.GetString(buffer, 0, data);&
Console.WriteLine(String.Format("Received: {0}", ch));
client.close();

推荐答案

你必须找到一种方法来告诉你的代码你正在接收什么,比如协议。首先,Tcp通信是字节的传输。这些字节有意义。它们是字符串的字符或一些编码的数字,如4个字节构成一个32位整数。

你可以设置你的tcp-Message的第一个字节作为一个代码告诉你你是什么得到:





you have to find a way to tell your code what you are receiving, like a protocol. In first place Tcp communication is a transport of bytes. these bytes have a meaning. Either they are the characters of a string or some encoded numbers, like 4 bytes make a 32bit integer.
you can set the very first byte of your tcp-Message as a code which tells you what you are getting like:


TcpListener server = new TcpListener(IPAddress.Any, Port);
Console.Write("Waiting for Client connection... ");
 
 TcpClient client = server.AcceptTcpClient();
 Console.WriteLine("\nClient Connected....!");
 
NetworkStream stream = client.GetStream();
 
byte[] buffer = new byte[client.ReceiveBufferSize];
int data = stream.Read(buffer, 0, client.ReceiveBufferSize);
switch (buffer[0]):
{
case 1: //now i am getting text
    string ch = Encoding.Unicode.GetString(buffer, 0, data);
    Console.WriteLine(String.Format("Received string: {0}", ch));
    break;
case 2: //now i am getting numbers
    int i=0;
    for (int x=1;x<5;x++){
        i=i<<8;
        i+=buffer[x];
    }
    Console.WriteLine(String.Format("Received int: {0}", i));
    break;
}
client.close();





当然你可以通过重复这个来填充一系列的整数每个int的小循环。所以你应该提前检查在那个tcp-message中编码了多少个int。当然,您需要在发送消息时插入第一个字节。



of course you can fill an array of ints by repeating that little loop for each int. so you should check in advance how many ints are encoded in that tcp-message. and of course you need to insert the first byte when sending the message.


这篇关于如何使用C#从客户端接收数据和套接字程序中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆