| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1991 人关注过本帖
标题:C# 网络通信 异步 数据接收失败 高手过来帮我看看~
只看楼主 加入收藏
caixiaoyi101
Rank: 1
等 级:新手上路
帖 子:9
专家分:0
注 册:2010-5-10
结帖率:0
收藏
 问题点数:0 回复次数:6 
C# 网络通信 异步 数据接收失败 高手过来帮我看看~
服务器端:
using System;
using System.Collections.Generic;
using
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using
using
using System.Threading;

namespace 异步通信服务器
{
    public partial class Form1 : Form
    {
        private Socket serversocket,clientsocket;
        private const int dataSize=1024;
        private byte[] data = new byte[dataSize];
            
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.button1.Enabled = false;
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            IPEndPoint server = new IPEndPoint(ip, 8000);
            serversocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            serversocket.Bind(server);
            serversocket.Listen(10);
            serversocket.BeginAccept(new AsyncCallback(AcceptConnection), serversocket);
        }
        private void AcceptConnection(IAsyncResult ar)
        {
            Socket oldServer = (Socket)ar.AsyncState;
            //异步接受传入的连接,并创建新的Socket来处理远程主机通信
            clientsocket = oldServer.EndAccept(ar);
            MessageBox.Show("与客户建立连接!");
            clientsocket.BeginReceive(data, 0, dataSize, SocketFlags.None, new AsyncCallback(ReceiveData), clientsocket);
        }
        private void ReceiveData(IAsyncResult ar)
        {
            Socket client = (Socket)ar.AsyncState;//client改成socketclient???
            try//就是这里,接收失败,显示“等待新客户!”
            {
                int receiveDataLength = client.EndReceive(ar);
                string str = System.Text.Encoding.Unicode.GetString(data, 0, receiveDataLength);
                this.richTextBox1.Text = str;
                clientsocket.BeginReceive(data, 0, dataSize, SocketFlags.None, new AsyncCallback(ReceiveData), clientsocket);//因为接收后还要继续准备接收,这样可以麽???
            }
            catch
            {
                client.Close();
                MessageBox.Show("等待新客户!");
                serversocket.BeginAccept(new AsyncCallback(AcceptConnection), serversocket);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                serversocket.Close();
                MessageBox.Show("停止监听!");
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message,"错误");
            }

        }
    }
}



客户端:
using System;
using System.Collections.Generic;
using
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using
using
using System.Threading;


namespace 异步通信客户端
{
    public partial class Form1 : Form
    {
        private Socket clientsocket;
        private const int datasize = 1024;
        private byte[] data = new byte[datasize];
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            IPEndPoint server = new IPEndPoint(ip, 8000);
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.BeginConnect(server, new AsyncCallback(ConnectServer), socket);
        }
        private void ConnectServer(IAsyncResult ar)
        {
            clientsocket = (Socket)ar.AsyncState;
            try
            {
                clientsocket.EndConnect(ar);
                MessageBox.Show("与服务器连接成功!");
                clientsocket.BeginReceive(data, 0, datasize, SocketFlags.None, new AsyncCallback(ReceiveData), clientsocket);
            }
            catch
            {
                MessageBox.Show("与服务器连接失败!");
            }

        }
        private void ReceiveData(IAsyncResult ar)
        {
            try
            {
                Socket server = (Socket)ar.AsyncState;
                int receiveDataLength = server.EndReceive(ar);
                string str = System.Text.Encoding.Unicode.GetString(data, 0, receiveDataLength);
                this.richTextBox1.Text = str;
            }
            catch
            { }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                int bytes = 0;
                Byte[] SendBytes = new Byte[256];
                string SendString = "123#";
                SendBytes = Encoding.ASCII.GetBytes(SendString.ToCharArray());
                bytes = clientsocket.Send(SendBytes, SendBytes.Length, 0);

             }
            catch
            {
                MessageBox.Show("发送失败!");
            }
        }
        
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                clientsocket.Close();
                MessageBox.Show("与服务器断开连接!");
            }
            catch
            {
                MessageBox.Show("连接尚未开始");
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                int bytes = 0;
                Byte[] SendBytes = new Byte[256];
                string SendString = "456#";
                SendBytes = Encoding.ASCII.GetBytes(SendString.ToCharArray());
                bytes = clientsocket.Send(SendBytes, SendBytes.Length, 0);

             }
            catch
            {
                MessageBox.Show("发送失败!");
            }
        }
        
    }
}
搜索更多相关主题的帖子: 网络 异步 数据 通信 
2010-05-16 15:21
乖老鼠
Rank: 5Rank: 5
来 自:四川省
等 级:职业侠客
威 望:2
帖 子:434
专家分:394
注 册:2008-9-8
收藏
得分:0 
你加个断点调试一下不就知道了。

clientsocket.BeginReceive(data, 0, dataSize, SocketFlags.None, new AsyncCallback(ReceiveData), clientsocket);
这里,最后一个参数clientsocket好像可以不要。

this.richTextBox1.Text = str;
这句不知道是不是存在多线程同步的问题。

我没试过,不知道错在哪里

转眼就从编程菜鸟混成了半灌水
2010-05-29 15:24
xueshui20
Rank: 5Rank: 5
等 级:职业侠客
威 望:1
帖 子:269
专家分:309
注 册:2009-4-19
收藏
得分:0 
你服务器是想通过一个委托来回调的吧,但是你的委托呢?
2010-05-30 08:15
zhouxiaoga
Rank: 1
等 级:新手上路
帖 子:10
专家分:3
注 册:2009-5-12
收藏
得分:0 
为什么不用同步呢 异步我不懂
2010-06-13 15:41
xinlite
Rank: 2
来 自:湖南长沙
等 级:论坛游民
帖 子:6
专家分:12
注 册:2010-6-13
收藏
得分:0 
异步通信要加入信号控制机制,是线程同步
2010-06-13 16:01
xinlite
Rank: 2
来 自:湖南长沙
等 级:论坛游民
帖 子:6
专家分:12
注 册:2010-6-13
收藏
得分:0 
你上面的代码,还没有等到响应信号就执行了,所以就报错了
2010-06-13 16:06
xinlite
Rank: 2
来 自:湖南长沙
等 级:论坛游民
帖 子:6
专家分:12
注 册:2010-6-13
收藏
得分:0 
参考 ManualResetEvent 类
2010-06-13 16:10
快速回复:C# 网络通信 异步 数据接收失败 高手过来帮我看看~
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.023615 second(s), 9 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved