C#网络编程错误

时间:2011-01-14 08:55:26

标签: c# sockets network-programming

不允许发送或接收数据的请求,因为套接字未连接且(使用sendto调用在数据报套接字上发送时)未提供地址。

我正在尝试使用套接字来创建一个非常简单的服务器/客户端。跟着这个。任何帮助是极大的赞赏 http://www.devarticles.com/c/a/C-Sharp/Socket-Programming-in-C-Part-I/1/

客户代码

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.Sockets;
using System.Net;
using System.Threading;

namespace ClientServer
{
    public partial class Form1 : Form
    {
        private byte[] m_Data = new byte[10];
        private Socket connection;
        private IAsyncResult m_asyncResult;
        private AsyncCallback pfnCallBack;
    public Form1()
    {
        InitializeComponent();
        connection = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
    }

    private void btn_connect_Click(object sender, EventArgs e)
    {
        makeConnection();
    }

    private void makeConnection()
    {
        IPAddress remoteMachineIP = IPAddress.Parse(ipAddress.Text);
        IPEndPoint remoteMachine = new IPEndPoint(remoteMachineIP, int.Parse(portNumber.Text));
        connection.Connect(remoteMachine);
        //WaitForData();
    }
    private void OnDataReceived(IAsyncResult asyn)
    {
        // Receive Ends
        int iRx = 0;
        iRx = connection.EndReceive(asyn);
        char[] chars = new char[iRx + 1];
        System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
        int charLen = d.GetChars(m_Data, 0, iRx, chars, 0);
        System.String szData = new System.String(chars);
    }

    private void WaitForData()
    {
        if (pfnCallBack == null)
            pfnCallBack = new AsyncCallback(OnDataReceived);
        m_asyncResult = connection.BeginReceive(m_Data, 0, m_Data.Length, SocketFlags.None, pfnCallBack, null);
    }

    private void send_Click(object sender, EventArgs e)
    {
        try
        {
            byte[] byData = System.Text.Encoding.ASCII.GetBytes(message.Text);
            connection.Send(byData);
        }
        catch (SocketException se)
        {
            MessageBox.Show(se.Message);
        }
    }
}

服务器代码

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.Sockets;
using System.Net;

namespace Server
{
    public partial class Form1 : Form
    {
        public Socket connection;
        public Socket m_socWorker;
        public IAsyncResult m_asynResult;
        public AsyncCallback pfnCallBack;
        byte[] m_DataBuffer = new byte[10];
        public Form1()
        {
            InitializeComponent();
        }

        private void btn_listen_Click(object sender, EventArgs e)
        {
            try
            {
            connection = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.IP);
            IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, int.Parse(portNumber.Text));
            connection.Bind(ipLocal);
            //Listening now
            connection.Listen(4);
            connection.BeginAccept(new AsyncCallback(OnClientConnect),null);
            }
            catch (SocketException se)
            {

            }
            txt_status.Text = "Listening";           
        }

        private void OnClientConnect(IAsyncResult asyn)
        {
            try
            {
                m_socWorker = connection.EndAccept(asyn);
                WaitForData(m_socWorker);
            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }

            txt_status.Text = "User Connected";
        }

        private void WaitForData(Socket m_socWorker)
        {
            if (pfnCallBack == null)
                pfnCallBack = new AsyncCallback(OnDataReceived);
            // now start to listen for any data...
            m_asynResult =
            connection.BeginReceive(m_DataBuffer, 0, m_DataBuffer.Length, SocketFlags.None, pfnCallBack, null);
        }

        public void OnDataReceived(IAsyncResult asyn)
        {
            txt_status.Text = "Data Received";
            //end receive...
            int iRx = 0;
            iRx = connection.EndReceive(asyn);
            char[] chars = new char[iRx + 1];
            System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
            int charLen = d.GetChars(m_DataBuffer, 0, iRx, chars, 0);
            System.String szData = new System.String(chars);
            dataReceived.Text = szData;
            WaitForData(m_socWorker);


        }
    }
}

0 个答案:

没有答案