簡體   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