首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

Socket通讯中Receive有关问题。

2013-07-16 
Socket通讯中Receive问题。。。问题是这样的1、对方首先发一段定长数据包,其中包括两个值a20,,b1或者02、b1

Socket通讯中Receive问题。。。
问题是这样的
1、对方首先发一段定长数据包,其中包括两个值a=20,,b=1或者0
2、b=1表示接下来对方还有有数据发来,b=0表示后面没数据了
3、a=20表示对方后面跟着20条记录,每条记录用回车符分割
4、每条记录长度不固定

前面那段定长的还好说,按长度接受就行了
关键是后面跟的a条记录,我应该怎样接受呢?
Socket刚接触,请解答详细点,谢谢
[解决办法]
using System; 
using System.Net; 
using System.Net.Sockets; 
using System.Text; 
namespace SocketServer 

/// <summary> 
/// Class1 的摘要说明。 
/// </summary> 
class Class1 

  /// <summary> 
  /// 应用程序的主入口点。 
  /// </summary> 
  //定义端口号 
  private const int porNum=81; 
  [STAThread] 
  static void Main(string[] args) 
  { 
   // 
   // TODO: 在此处添加代码以启动应用程序 
   // 
   bool done=false; 
   TcpListener listener=new TcpListener(porNum); 
   listener.Start(); 
   while(!done){ 
   Console.Write("正在侦听81端口..."); 
    TcpClient client=listener.AcceptTcpClient(); 
    Console.WriteLine("\n处理连接请求..."); 
    NetworkStream ns=client.GetStream(); 
    //ns.Read(,0,); 
    byte[] bytes=new byte[1024]; 
    int bytesRead=ns.Read(bytes,0,bytes.Length); 
    Console.WriteLine(Encoding.BigEndianUnicode.GetString(bytes,0,bytesRead)); 
    byte[] byteTime=Encoding.ASCII.GetBytes(DateTime.Now.ToString()); 
    try 
    { 
     ns.Write(byteTime,0,byteTime.Length); 
     ns.Close(); 
     client.Close(); 
    } 
    catch(Exception ex){ 
    Console.WriteLine(ex.ToString()); 
    } 


   } 
   listener.Stop(); 
  } 



Web客户端 

添加命名空间: 
using System.Net; 
using System.Net.Sockets; 
using System.Text; 

连接代码: 
private void socketButton_Click(object sender, System.EventArgs e) 
  {//连接服务器程式 
   try 
   { 
    //开始连接 
    TcpClient client=new TcpClient("192.168.0.100",81); 
    NetworkStream ns=client.GetStream(); 
    byte[] byteTime=Encoding.BigEndianUnicode.GetBytes("客户端数据提交\n"); 
    ns.Write(byteTime,0,byteTime.Length); 
    //返回客户端信息 
    byte[] clientIp=Encoding.BigEndianUnicode.GetBytes("客户端IP地址:"+Request.UserHostAddress+"\n"); 
    ns.Write(clientIp,0,clientIp.Length); 
    byte[] bytes=new byte[1024]; 
    int bytesRead=ns.Read(bytes,0,bytes.Length); 
    showLabel.Text="服务器返回信息"+Encoding.ASCII.GetString(bytes,0,bytesRead); 
    client.Close(); 
   } 
   catch(Exception ex) 
   { 
    showLabel.Text="抛出异常"+ex.ToString(); 
   } 
   finally{} 
  }
仅供参考
[解决办法]
比较方便的做法就是用StreamReader,它支持ReadLine。
你可以用它来读TcpClient的NetworkStream。

或者,你也可以做一个状态机:


class LineReciever
{
    int linesToRecive = 20;
    List<byte> unprocessed = new List<byte>();

    public bool OnReceive(byte[] bytes)
    {
        int count = Array.IndexOf(bytes, '\n') + 1;

        unprocessed.AddRange(bytes.Take(count));
        bytes = bytes.Skip(count).ToArray();

        if (count > 0)
        {
            OnLineRecieved(Encoding.UTF8.GetString(unprocessed.ToArray()));
            unprocessed.Clear();


            if (--linesToRecive == 0) return true;
            else return OnReceive(bytes);
        }
        unprocessed.AddRange(bytes);
        return false;
    }
            
    public void OnLineRecieved(string line)
    {
        MessageBox.Show(line);
    }
}


[解决办法]
不管什么内容,都可以转换为byte[]发送,接收到数据后,根据自己的规则,把数据恢复出来就行
[解决办法]
接收下来放到 MemoryStream 中,同时统计回车符,满了就可以解析了。
注意要设接收超时,免得收不到死机了。
[解决办法]
首先要确定用TCP还是UDP

如果用TCP的话 先把接收到的数据(byte[])存进一个缓冲区  然后再从缓冲区中去找完整的数据包

如果是UDP的话 好说 每一次Receive到的数据都是完整的


以上两种都需要自己定义数据格式(通信协议)

详细参照:参看

热点排行