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

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

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

}

/// 异步连接客户端

///

///

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

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值