码迷,mamicode.com
首页 > 其他好文 > 详细

socket 异步接收连接和接收数据

时间:2019-05-24 12:45:01      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:cps   highlight   gate   none   thread   threading   mode   got   address   

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using Newtonsoft.Json;
namespace WindowsSocket
{
	public class Msg
	{
		public int Flag { get; set; }
		public string Message { get; set; }
	}
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
		}
		//如果一次接收不了,会多次进入OnMessage方法解析
		byte[] buffer = new byte[1024];
		public void OnMessage(IAsyncResult result)
		{
			//result.AsyncState 为调用BeginReceive 传递过来的参数
			Socket ts = (Socket)result.AsyncState;
			//获取接收到信息的长度
			//int count = ts.EndReceive(result);
			//result.AsyncWaitHandle.Close();
			this.textBox1.Invoke(new EventHandler(delegate
			{
				var msg = Encoding.ASCII.GetString(buffer);
				MessageBox.Show(msg);
				//var objects = JsonConvert.DeserializeObject<Msg>(msg);
				//MessageBox.Show(objects.Flag.ToString());
				//MessageBox.Show(objects.Message.ToString());
				//textBox1.Text += ts.RemoteEndPoint.ToString() + "客户端信息" + Encoding.ASCII.GetString(buffer) + "\r\n";
			}));
			ts.Send(Encoding.ASCII.GetBytes("How are you? I got a message"));
			//清空数据,重新开始异步接收
			//buffer = new byte[buffer.Length];

			ts.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnMessage), ts);
		}

		/// 异步连接客户端
		/// </summary>
		/// <param name="tcpServer"></param>
		private void AsynAccept(Socket tcpServer)
		{
			tcpServer.BeginAccept(asyncResult =>
			{
				//取得终端Socket
				Socket socketAccept = tcpServer.EndAccept(asyncResult);
				//获取客户端地址信息
				if (socketAccept.RemoteEndPoint is IPEndPoint)
				{

					//var ss = tcpClient.Receive(buffer);
					//异步获取数据
					socketAccept.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnMessage), socketAccept);

					//byte[] msg = new byte[tcpServer.ReceiveBufferSize];
					//tcpServer.Receive(msg);
					//textBox1.Invoke(new EventHandler(delegate
					//{
					//	textBox1.Text += "客户端信息" + tcpClient.RemoteEndPoint.ToString() + "\r\n";
					//}));

				}
				//持续监听终端连接
				AsynAccept(tcpServer);

			}, null);
		}
		//开启socket服务端
		private void button1_Click(object sender, EventArgs e)
		{
			Task task = new Task(() =>
			{
				Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
				socket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8877));
				socket.Listen(1111);
				AsynAccept(socket);
			});
			task.Start();

		}
	}
}

  

socket 异步接收连接和接收数据

标签:cps   highlight   gate   none   thread   threading   mode   got   address   

原文地址:https://www.cnblogs.com/wlzhang/p/10917237.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!