c# socket 异步

2 篇文章 0 订阅

http://download.csdn.net/detail/qq_15572445/9471828



客户端:

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

namespace Socket_Client_asynchronous
{
    public partial class Form1 : Form
    {
        public TcpClient tcpc; //对服务器端建立TCP连接 
        public Socket tcpsend; //发送创建套接字 
        public bool connect_flag = false; 
        public byte[] receive_buff = new byte[4096]; 
        public ManualResetEvent connectDone = new ManualResetEvent(false); //连接的信号 
        public ManualResetEvent readDone = new ManualResetEvent(false); //读信号 
        public ManualResetEvent sendDone = new ManualResetEvent(false); //发送结束
        public bool connect(string address)
        { 
            try 
            {
                tcpsend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//初始化套接字
                IPEndPoint remotepoint = new IPEndPoint(IPAddress.Parse(address), Convert.ToInt32(textBox3.Text));//根据ip地址和端口号创建远程终结点
                EndPoint end = (EndPoint)remotepoint; 
                tcpsend.BeginConnect(end, new AsyncCallback(ConnectedCallback), tcpsend); //调用回调函数
                connectDone.WaitOne(); 
                return true;
            } 
            catch 
            { 
                return false;
            }
        }
        private void ConnectedCallback(IAsyncResult ar)
        {
            Socket client = (Socket)ar.AsyncState;
            client.EndConnect(ar);
            connect_flag = true;
            connectDone.Set();
        }
        public void send(string data)
        {
            int length = data.Length;
            Byte[] Bysend = new byte[length];
            Bysend = System.Text.Encoding.GetEncoding("GB2312").GetBytes(data); //将字符串指定到指定Byte数组
            tcpsend.BeginSend(Bysend, 0, Bysend.Length, 0, new AsyncCallback(SendCallback), tcpsend); //异步发送数据
            sendDone.WaitOne();
        }
        private void SendCallback(IAsyncResult ar) //发送的回调函数
        {
            Socket client = (Socket)ar.AsyncState;
            int bytesSend = client.EndSend(ar); //完成发送
            sendDone.Set();
        }
        public void receive() //接收数据
        {
            //byte[] receive=new byte[1024];
            tcpsend.BeginReceive(receive_buff, 0, receive_buff.Length, 0, new AsyncCallback(ReceiveCallback), tcpsend);
            //sendDone.WaitOne();
        }
        
        private void ReceiveCallback(IAsyncResult ar)
        {
            Socket client = (Socket)ar.AsyncState; //获取句柄
            int bytesread = client.EndReceive(ar);
            if (bytesread > 0)
            {
                tcpsend.BeginReceive(receive_buff, 0, receive_buff.Length, 0, new AsyncCallback(ReceiveCallback), client);
            }
            else
            {
                readDone.Set();
            }
            /*
            Socket client = (Socket)ar.AsyncState; //获取句柄 
            int bytesread = client.EndReceive(ar); 
            if (bytesread > 0)
            {
                client.BeginReceive(receive_buff, 0, receive_buff.Length, 0, new AsyncCallback(ReceiveCallback), client);
                string content = Encoding.GetEncoding("GB2312").GetString(receive_buff, 0, receive_buff.Length);
                richTextBox2.Text = content;
                //richTextBox2.Text = Encoding.ASCII.GetString(receive_buff, 0, receive_buff.Length);
                //send.tcpsend.Close();

            } 
            else 
            {
                readDone.Set();
            }
         */
        }
        public Form1()
        {
            InitializeComponent();
        }

        private void btnAvaliable_Click(object sender, EventArgs e)
        {
            connectDone.Reset(); 
            if (connect(textBox2.Text) == true) 
            { 
                connectDone.WaitOne(); 
                textBox1.Text = "成功连接远程计算机"; 
            } 
            else 
            { 
                textBox1.Text = "连接失败"; 
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try { 
                // sendDone.Reset();
                send(richTextBox1.Text); 
                // sendDone.WaitOne();
                textBox1.Text = "发送成功"; 
                 readDone.Reset();
                //receive(); 
                 //readDone.WaitOne(); 
                 byte[] back = new byte[1024]; 
                int count = tcpsend.Receive((back));
                richTextBox2.Text = Encoding.GetEncoding("GB2312").GetString(back, 0, count); 
                //tcpsend.Close();
            } 
            catch 
            {
                textBox1.Text = "发送异常";
            }
        }

        private void Form1_Leave(object sender, EventArgs e)
        {
            tcpsend.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }
    }
}


服务端:

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


namespace Socket_Server_asynchronous
{
    public partial class Form1 : Form
    {
        public int port = 8000;
        public Thread threadread;
        public IPEndPoint tcplisener;//将网络端点表示为IP地址和端口号
        public bool listen_flag = false;
        public Socket read;
        public string server_ip = "127.0.0.1";
        public Thread accept;//创建并控制线程

        public ManualResetEvent AcceptDone = new ManualResetEvent(false); //连接的信号

        public Form1()
        {
            InitializeComponent();
        }

        private void btnLink_Click(object sender, EventArgs e)
        {
            IPAddress ip = IPAddress.Parse(server_ip);
            //用指定ip和端口号初始化
            tcplisener = new IPEndPoint(ip, port); 
            //创建一个socket对象
            read = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            read.Bind(tcplisener); //绑定
            ///收到客户端的连接,建立新的socket并接受信息
            read.Listen(500); //开始监听
            textBox1.Text = " 等待客户端连接";
            accept = new Thread(new ThreadStart(Listen));
            accept.Start();
            //  Listen();
            GC.Collect();//即使垃圾回收
            GC.WaitForPendingFinalizers();

        }
        public void Listen()
        {
            Thread.CurrentThread.IsBackground = true; //后台线程
            try
            {
                while (true)
                {
                    AcceptDone.Reset();
                    //Socket temp_socket = read.Accept();
                    read.BeginAccept(new AsyncCallback(AcceptCallback), read);  //异步调用
                    AcceptDone.WaitOne();
                }
            }
            catch (Exception er)
            {
                MessageBox.Show(er.Message);
            }
        }
        public void AcceptCallback(IAsyncResult ar) //accpet的回调处理函数
        {
            AcceptDone.Set();
            Socket temp_socket = (Socket)ar.AsyncState;
            Socket client = temp_socket.EndAccept(ar); //获取远程的客户端
            Control.CheckForIllegalCrossThreadCalls = false;
            textBox1.Text = "建立连接";
            IPEndPoint remotepoint = (IPEndPoint)client.RemoteEndPoint;//获取远程的端口
            string remoteaddr = remotepoint.Address.ToString();        //获取远程端口的ip地址
            textBox1.Text = "接收来自" + remoteaddr + "的连接";

            StateObject state = new StateObject();
            state.workSocket = client;
            client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
        }

        public void ReadCallback(IAsyncResult ar)
        {
            String content = String.Empty;

            // Retrieve the state object and the handler socket
            // from the asynchronous state object.
            StateObject state = (StateObject)ar.AsyncState;
            Socket handler = state.workSocket;

            // Read data from the client socket. 
            int bytesRead = handler.EndReceive(ar);

            if (bytesRead > 0)
            {
                string contentstr = ""; //接收到的数据
                contentstr += Encoding.GetEncoding("GB2312").GetString(state.buffer, 0, bytesRead);
                richTextBox1.Text += contentstr+"\r\n";
                byte[] byteData = Encoding.GetEncoding("GB2312").GetBytes("Success:" + contentstr);//回发信息
                handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
                handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
            }
        }
        private void Send(Socket handler, String data)
        {
            // Convert the string data to byte data using ASCII encoding.
            byte[] byteData = Encoding.GetEncoding("GB2312").GetBytes(data);

            // Begin sending the data to the remote device.
            handler.BeginSend(byteData, 0, byteData.Length, 0,
                new AsyncCallback(SendCallback), handler);
        }

        private void SendCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                //     Socket handler = (Socket)ar.AsyncState;
                // Complete sending the data to the remote device.
                //      int bytesSent = handler.EndSend(ar);
                // Console.WriteLine("Sent {0} bytes to client.", bytesSent);
                //      richTextBox1.Text = "Send" + bytesSent.ToString() + "bytes to client.";
                //      handler.Shutdown(SocketShutdown.Both);
                //     handler.Close();
            }

            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
        public class StateObject
        {
            // Client  socket.
            public Socket workSocket = null;
            // Size of receive buffer.
            public const int BufferSize = 1024;
            // Receive buffer.
            public byte[] buffer = new byte[BufferSize];
            // Received data string.
            public StringBuilder sb = new StringBuilder();
        }


    }
}




http://download.csdn.net/detail/qq_15572445/9471828

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#Socket 类库提供了异步操作的支持,这可以使我们更加高效地处理网络通信。在 Socket 类库中,异步操作包括异步发送异步接收。 下面是一个简单的异步发送的示例代码: ```csharp using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; class Program { static void Main(string[] args) { string hostname = "www.example.com"; int port = 80; IPAddress[] ips = Dns.GetHostAddresses(hostname); IPEndPoint remoteEP = new IPEndPoint(ips[0], port); Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); byte[] sendData = Encoding.ASCII.GetBytes("Hello, world!"); clientSocket.BeginConnect(remoteEP, (result) => { clientSocket.EndConnect(result); clientSocket.BeginSend(sendData, 0, sendData.Length, SocketFlags.None, (sendResult) => { int bytesSent = clientSocket.EndSend(sendResult); Console.WriteLine("Sent {0} bytes to server.", bytesSent); clientSocket.Shutdown(SocketShutdown.Both); clientSocket.Close(); }, null); }, null); Console.ReadLine(); } } ``` 在上面的代码中,我们创建了一个 Socket 对象,然后使用 BeginConnect 方法异步连接到远程主机。在连接完成后,我们使用 BeginSend 方法异步发送数据。发送完成后,我们关闭 Socket 对象。 需要注意的是,异步操作通常是通过回调函数来完成的,这些回调函数都是在另一个线程中执行的。因此,在使用异步操作时,需要特别注意线程安全问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值