C#中的聊天应用程序

时间:2014-01-29 08:24:59

标签: c# winforms sockets chat

我已尝试使用此代码制作聊天应用程序。当我运行应用程序时,我得到一个Exception: A request to send or receive data was disallowed because the socket is not connected和(当使用sendto调用发送数据报套接字时)no address was supplied

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());

            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

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

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

您还必须将套接字绑定到本地IPEndpoint。使用函数SendTo()发送数据报时,将使用远程IPEndpoint

答案 1 :(得分:0)

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

创建套接字

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

完成前三个步骤后,就会建立套接字连接,你需要使用该连接来发送和接收系统调用。这意味着,前三个列出的点是"做一次"只有你将使用它来进行任何次数的发送和接收呼叫,直到最后关闭连接。

This link会帮助你进一步..