1,首先添加两个windows窗体项目,一个作为服务端server,一个作为客户端Client
2,然后添加服务端代码,添加命名空间,界面上添加TextBox控件
using
System.Net;
using System.Net.Sockets;
3,FormLoad方法添加代码
private
void Form1_Load(object sender, EventArgs e)
{
IPEndPoint epServer =
new IPEndPoint(IPAddress.Parse("127.0.0.1"), 7878);//IP地址和端口号
Socket socket
= new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);//定义socket
socket.Bind(epServer);//绑定
socket.Listen(10);//监听
socket.BeginAccept(new
AsyncCallback(RecVing),
socket);//异步接收,回调方法为RecVing
}
4,添加回调方法代码
private void
RecVing(IAsyncResult rec_socket)
{
string cmdstr = "";
Socket sc
= (Socket)rec_socket.AsyncState;
Socket socket =
sc.EndAccept(rec_socket);
byte[] bytes = new byte[1024];
int i =
socket.Receive(bytes);
cmdstr = Encoding.UTF8.GetString(bytes, 0,
i);
showstrs(cmdstr);
sc.BeginAccept(new AsyncCallback(RecVing),
sc);
}
5,添加showstrs方法,
定义委托private delegate void
shixudong_invoke(string invokefun);
private void showstrs(string
recv_strs)
{
if (recv_strs.Length != 0)
{
if
(this.InvokeRequired)
{
shixudong_invoke invoke = new
shixudong_invoke(showstrs);
this.Invoke(invoke,
(object)recv_strs);
}
else
{
textBox1.Text =
recv_strs;
}
}
}
6,到此为止,服务端已经添加完毕
7,客户端代码,首先跟服务端一样,添加命名空间,在界面上添加button事件
private
void button1_Click(object sender, EventArgs e)
{
IPEndPoint IPEndPoint
= new IPEndPoint(IPAddress.Parse("127.0.0.1"), 7878);//IP,端口号
Socket socket
= new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
socket.BeginConnect(IPEndPoint, new
AsyncCallback(Sending),
socket);//回调方法Sending
}
8,添加回调方法,代码如下
private void
Sending(IAsyncResult rec_socket)
{
Socket socket =
(Socket)rec_socket.AsyncState;
try托福答案
{
if
(socket.Connected)
{
byte[] msgBuff =
Encoding.UTF8.GetBytes(textBox1.Text);
socket.Send(msgBuff);
//socket.Accept();
}
else
{
Console.WriteLine("Error!",
"Error!");
}
}
catch
{
Console.WriteLine("Error!",
"Error!");
}
}
9,到此为止,客户端代码已经完成,调试的时候先启动服务端,然后启动客户端
相关文章
- 12-26.net平台下socket异步通讯
- 12-26c++Socket 异步通讯
- 12-26.net平台下socket异步通讯
- 12-26你应该知道的.net平台下socket异步通讯(代码实例)
- 12-26VisaulStudio2019下用VB.net实现socket与西门子PLC进行通讯案例
- 12-26vb.net子线程调用winhttp进行通讯同步和异步的对比
- 12-26C# Socket的TCP通讯 异步 (2015-11-07 10:07:19)转载▼
- 12-26.net平台下C#socket通信(中)
- 12-26基于Socket通讯(C#)和WebSocket协议(net)编写的两种聊天功能(文末附源码下载地址)
- 12-26C#.NET通过Socket实现平行主机之间网络通讯(含图片传输的Demo演示)