繁体   English   中英

C#中的聊天应用程序

[英]Chat application in C#

我已经尝试过使用此代码制作聊天应用程序。 当我运行该应用程序时,出现Exception: A request to send or receive data was disallowed because the socket is not connected并且(在使用sendto调用在数据报套接字上发送时) no address was supplied Exception: A request to send or receive data was disallowed because the socket is not connected

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;


namespace client_chatApplication
{
    public partial class Form1 : Form
    {
        Socket sck;
        EndPoint epLocal, epRemote;
        public Form1()
        {
            InitializeComponent();
            sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            textLocalIP.Text = GetLocalIp();
            textFriendsIP.Text = GetLocalIp();
        }

        //to get the local ip address
        private string GetLocalIp()
        {
            IPHostEntry host;
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    return ip.ToString();
                }
            }
            return "127.0.0.1";
        }

        public void MessageCallBack(IAsyncResult aresult)
        {
            try
            {
                int size = sck.EndReceiveFrom(aresult, ref epRemote);
                if (size > 0)
                {
                    byte[] receivedData = new byte[1464];

                    receivedData = (byte[])aresult.AsyncState;
                    ASCIIEncoding eEncoding = new ASCIIEncoding();
                    string receivedMessage = eEncoding.GetString(receivedData);
                    listMessage.Items.Add("fiend" + receivedMessage);
                }
                byte[] buffer = new byte[1500];
                sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.ToString());

            }
        }
        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {

        }

        private void textLocalIP_TextChanged(object sender, EventArgs e)
        {
            try
            {

                System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
                byte[] msg = new byte[1500];
                msg = enc.GetBytes(textMessage.Text);
                sck.Send(msg);
                listMessage.Items.Add("yoy" + textMessage.Text);
                textMessage.Clear();

            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.ToString());
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                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.Bind(epRemote);

                byte[] buffer = new byte[1500];
                Socket dataSocket = AsyncSocket.EndAccept(_IAsyncResult);
                sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
                button1.Text = "connected";
                button1.Enabled = false;
                button2.Enabled = true;
                textMessage.Focus();
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());

            }
        }
    }
}

您创建了套接字,但创建后未将其绑定到端口。 您想发送数据时将其绑定。

仅当您要发送数据时绑定是不正确的行为。

您还只需要将套接字绑定到本地IPEndpoint 当您使用功能SendTo()发送数据IPEndpoint将使用远程IPEndpoint

使用套接字涉及以下基本步骤:

创建套接字

  • 绑定到网络接口
  • 监听连接或建立套接字连接
  • 拨打和接听电话

完成前三个步骤后,便建立了套接字连接,您将需要使用该连接进行发送和接收系统调用。这意味着,列出的前三个点仅“执行一次”,您将使用它来进行多次发送和接收呼叫,直到最终关闭连接。

该链接将进一步帮助您。

暂无
暂无

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

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