如何使用C#从客户端接收数据和套接字程序中的字符

编程入门 行业动态 更新时间:2024-10-26 06:27:28
本文介绍了如何使用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#从客户端接收数据和套接字程序中的字符

本文发布于:2023-10-26 19:16:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531101.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   客户端   字符   程序   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!