繁体   English   中英

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

[英]Change Protocol from UDP to TCP in a simple chat application

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

我声明了这些对象:

Socket sck;
EndPoint epLocal, epRemote;

并在构造函数中初始化它们:

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

我在启动Connection的按钮中有此按钮:

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协议的方式。 谢谢!

有什么原因不能只使用ProtocolType.Tcp吗?

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

和博客可以帮助您

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM