2 u010867034 u010867034 于 2013.09.27 15:15 提问

.Net UDP Socket 通讯时 如何实现客户端连续发信息或服务端连续发信息

本人是新手,写了 C# 的UDP SOcket 通讯程序,目前只实现了 客户端向服务端发送消息,服务端收到消息后回复消息,而 不能实现客户端连续向服务端发消息,服务端连续回复消息。
在查找资料说要使用多线程,但是我不懂,请求高手指导。代码如下:
Client:
private void btSendMsg_Click(object sender, EventArgs e)
{
byte[] data = new byte[1024];

        string input;

        //设置服务IP,设置端口号
        IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(txtServerIP.Text.ToString()), 8001);


        //定义网络类型,数据连接类型和网络协议UDP
        Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

        string welcome = "Hello! ";
        data = Encoding.ASCII.GetBytes(welcome);
        server.SendTo(data, data.Length, SocketFlags.None, ipep);
        IPEndPoint senderIP = new IPEndPoint(IPAddress.Any, 0);
        EndPoint Remote = (EndPoint)senderIP;
        data = new byte[1024];
         int recv = server.ReceiveFrom(data, ref Remote);

            input = txtSend.Text;

            server.SendTo(Encoding.ASCII.GetBytes(input), Remote);
            data = new byte[1024];
            recv = server.ReceiveFrom(data, ref Remote);

            txtRec.Text = Encoding.ASCII.GetString(data, 0, recv);
                   server.Close();
    }

Server:
private void btRec_Click(object sender, EventArgs e)
{
int recv;
byte[] data = new byte[1024];

        //得到本机IP,设置端口号         
        IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 8001);
        Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        newsock.Bind(ipep);
        //得到客户机IP
        IPEndPoint senderIP = new IPEndPoint(IPAddress.Any, 0);
        EndPoint Remote = (EndPoint)(senderIP);
        recv = newsock.ReceiveFrom(data, ref Remote);
        string welcome = "Welcome ! ";

        //字符串与字节数组相互转换
        data = Encoding.ASCII.GetBytes(welcome);
        string strReturn;

        data1 = Encoding.ASCII.GetBytes(strReturn);
        //发送信息
        newsock.SendTo(data, data.Length, SocketFlags.None, Remote);

        data = new byte[2048];
        //发送接受信息
        recv = newsock.ReceiveFrom(data, ref Remote);
        txtSerRev.Text = (Encoding.ASCII.GetString(data, 0, recv));
        newsock.SendTo(data, data.Length, SocketFlags.None, Remote);
    }
Csdn user default icon
上传中...
上传图片
插入图片