在简单的聊天应用程序中将协议从UDP更改为TCP

时间:2013-12-02 16:15:35

标签: c# sockets tcp udp

我想更改我用于简单聊天应用程序的协议,使用UDP来使用TCP协议。

我宣布了这些对象:

Socket sck;
EndPoint epLocal, epRemote;

并在构造函数中使用:

初始化它们
sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

我在启动连接的按钮中有这个:

private void btn_Start_Click(object sender, EventArgs e) {
    epLocal = new IPEndPoint(IPAddress.Parse(textLocalIp.Text),Convert.ToInt32(textLocalPort.Text));
    sck.Bind(epLocal);

    epRemote = new IPEndPoint(IPAddress.Parse(textFriendsIp.Text), Convert.ToInt32(textFriendsPort.Text));
    sck.Connect(epRemote);

    byte[] buffer = new byte[1500];
    sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
}

并在发送消息按钮中单击:

private void btn_Send_Click(object sender, EventArgs e){
    System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
    byte[] msg = new byte[1500];
    msg = enc.GetBytes(textMessage.Text);
    sck.Send(msg);
}

这是“CallBack”方法:

private void MessageCallBack(IAsyncResult aResult){
    int size = sck.EndReceiveFrom(aResult, ref epRemote);
    if (size > 0){
        byte[] recievedData = new byte[1464];
        recievedData = (byte[])aResult.AsyncState;
        ASCIIEncoding eEncoding = new ASCIIEncoding();
        string recievedMessage = eEncoding.GetString(recievedData);
        listMessage.Items.Add("Friend: "+recievedMessage);
    }
    byte [] buffer = new byte[1500];
    sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
}

所以我应该改变什么来使用UDP协议来使用TCP协议。 谢谢!

1 个答案:

答案 0 :(得分:0)

您有什么理由不能使用ProtocolType.Tcp

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

和博客帮助你

http://netrsc.blogspot.com/2010/05/using-asynchronous-sockets.html