使用AweSocket 收发消息
public Form1()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
private void ListenInBlockIOMode()
{
Task.Run(() =>
{
var listenSocket = AweSock.TcpListen(_listeningPort);
while (true)
{
var client = AweSock.TcpAccept(listenSocket);
var inBuf = AwesomeSockets.Buffers.Buffer.New();
var received = AweSock.ReceiveMessage(client, inBuf);
AwesomeSockets.Buffers.Buffer.FinalizeBuffer(inBuf);
var msg = Encoding.UTF8.GetString(AwesomeSockets.Buffers.Buffer.GetBuffer(inBuf)).Replace("\0", "");
txtContent.AppendText("\r\n" + msg);
}
});
}
private void btnSend_Click(object sender, EventArgs e)
{
try
{
var server = AweSock.TcpConnect(txtIP.Text, int.Parse(txtSendPort.Text));
var outBuf = AwesomeSockets.Buffers.Buffer.New();
AwesomeSockets.Buffers.Buffer.ClearBuffer(outBuf);
AwesomeSockets.Buffers.Buffer.Add(outBuf, txtSend.Text);
AwesomeSockets.Buffers.Buffer.FinalizeBuffer(outBuf);
int bytesSent = AweSock.SendMessage(server, outBuf);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "", MessageBoxButtons.OK);
}
}
private int _listeningPort;
private void Form1_Load(object sender, EventArgs e)
{
_listeningPort = int.Parse(ConfigurationManager.AppSettings["listeningPort"]);
Text = string.Format("Listening : {0}", _listeningPort);
ListenInBlockIOMode();
}
UI :