发送二进制数据和读取,使用异步socket编程的值 [英] Send binary data and read the values of that using async socket programming

查看:178
本文介绍了发送二进制数据和读取,使用异步socket编程的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将数据从我的客户端.the将消息发送到服务器发送到服务器,每一个消息是 36字节,并在此消息每4个字节一个领域,在服务器的一部分,我应该能够检测从消息客户端发送场.Suppose我有这样的数据:

I am trying to send data to a server from my client .the client sends messages to a server ,every message is 36 bytes and in this message every 4 byte is a field and in server part i should be able to detect that field from the message that client sends .Suppose i have this data :

A=21
B=32
c=43
D=55
E=75
F=73
G=12
H=14
M=12

在客户端作为一个单一的消息。正如你可以看到我的消息有9场,每场 4字节整数键,所有的消息是我应该把这个值 36字节

In the client i should send this values as a single message .as you can see my message has 9 field and every field is 4 byte integer and all message is 36 byte.

因此​​,在服务器部分,当收到消息我应该能够分开的消息,并找到字段的值。

So in server part when the message is received i should be able to separate the message and find the value of the fields .

在客户端应用程序我使用这个结构来发送邮件到我的服务器:

In client application i am using this structure to send message to my server :

 m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // Cet the remote IP address
            IPAddress ip = IPAddress.Parse(GetIP());
            int iPortNo = System.Convert.ToInt16("12345");
            // Create the end point 
            IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo);
            // Connect to the remote host
            m_clientSocket.Connect(ipEnd);
    if (m_clientSocket.Connected)
                {

                    Object objData = ?!!!!;//My message
                    byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());
                    if (m_clientSocket != null)
                    {
                        m_clientSocket.Send(byData);
                    }
                    Thread.Sleep(4000);

            }
}

和在服务器部分我用这code接收数据:

And in server part i am using this code to receive the data:

public void OnDataReceived(IAsyncResult asyn)
        {
            try
            {
                SocketPacket socketData = (SocketPacket)asyn.AsyncState;

                int iRx = 0;
                // Complete the BeginReceive() asynchronous call by EndReceive() method
                // which will return the number of characters written to the stream 
                // by the client
                iRx = socketData.m_currentSocket.EndReceive(asyn);
                char[] chars = new char[iRx + 1];
                System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
                int charLen = d.GetChars(socketData.dataBuffer,
                                         0, iRx, chars, 0);
                System.String szData = new System.String(chars);
                MessageBox.Show(szData);

                // Continue the waiting for data on the Socket
                WaitForData(socketData.m_currentSocket);
            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
            }
            catch (SocketException se)
            {
            }
        }

下面是我的服务器code的另一部分:

Here is the other part of my server code :

 public void OnClientConnect(IAsyncResult asyn)
        {
            try
            {
                // Here we complete/end the BeginAccept() asynchronous call
                // by calling EndAccept() - which returns the reference to
                // a new Socket object
                m_workerSocket[m_clientCount] = m_mainSocket.EndAccept(asyn);
                // Let the worker Socket do the further processing for the 
                // just connected client
                WaitForData(m_workerSocket[m_clientCount]);
                // Now increment the client count
                ++m_clientCount;
                // Display this client connection as a status message on the GUI    
                String str = String.Format("Client # {0} connected", m_clientCount);


                // Since the main Socket is now free, it can go back and wait for
                // other clients who are attempting to connect
                m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
            }


        }
        public class SocketPacket
        {
            public System.Net.Sockets.Socket m_currentSocket;
            public byte[] dataBuffer = new byte[36];
        }

在我的的Form_Load 服务器部分的我有这个code:

In my form_load of server part i have this code:

    ipaddress = GetIP();
    // Check the port value

    string portStr = "12345";
    int port = System.Convert.ToInt32(portStr);
    // Create the listening socket...
    m_mainSocket = new Socket(AddressFamily.InterNetwork,
                              SocketType.Stream,
                              ProtocolType.Tcp);
    IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);
    // Bind to local IP Address...
    m_mainSocket.Bind(ipLocal);
    // Start listening...
    m_mainSocket.Listen(4);
    // Create the call back for any client connections...
    m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);

其实我想实现此链接:

in fact i am trying to implement this link :

<一个href=\"http://www.$c$cguru.com/csharp/csharp/cs_misc/sampleprograms/article.php/c7695/Asynchronous-Socket-Programming-in-C-Part-I.htm\" rel=\"nofollow\">http://www.$c$cguru.com/csharp/csharp/cs_misc/sampleprograms/article.php/c7695/Asynchronous-Socket-Programming-in-C-Part-I.htm

我的问题是我怎样才能把我的消息作为36字节通过客户端,并得到从服务器分开呢?

My problem is how can i send my message as a 36 bytes via client and get and separate that from server ?

每四个字节是一个领域,我应该能够得到这个值。

Every four bytes is a field and i should be able to get this value .

推荐答案

好像你需要的是2种方法整数转换为字节数组,反之亦然:

Seems like all you need is 2 methods to convert integers to byte-array and vice versa:

byte[] packet =  CreateMessage(21,32,43,55,75,73,12,14,12);
//send message
//recv message and get ints back
int[] ints =  GetParameters(packet);

...

public byte[] CreateMessage(params int[] parameters)
{
    var buf = new byte[parameters.Length * sizeof(int)];
    for (int i = 0; i < parameters.Length; i++) 
        Array.Copy(BitConverter.GetBytes(parameters[i]), 0, buf, i * sizeof(int), sizeof(int));
    return buf;
}

public int[] GetParameters(byte[] buf)
{
    var ints = new int[buf.Length / sizeof(int)];
    for (int i = 0; i < ints.Length; i++)
        ints[i] = BitConverter.ToInt32(buf, i * sizeof(int));
    return ints;
}

这篇关于发送二进制数据和读取,使用异步socket编程的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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