服务器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
namespace ConsoleApplication11
{
class Program
{
static void Main(string[] args)
{
Socket ServerSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
IPEndPoint serIP = new IPEndPoint(IPAddress.Parse("127.0.0.1"),8000);
ServerSocket.Bind(serIP);
ServerSocket.Listen(0);
Console.WriteLine("服务器已开始监听");
asyncAccept(ServerSocket);
Console.Read();
}
public static void asyncAccept(Socket Ser) {
Ser.BeginAccept(asyncResult =>
{
Socket Client = Ser.EndAccept(asyncResult);
asyncSend(Client,"当前设备已连接");
asyncRecive(Client);
asyncAccept(Ser);
}, null);
}
public static void asyncRecive(Socket ser){
byte[] data = new byte[1024];
ser.BeginReceive(data, 0, data.Length, SocketFlags.None, asyncResult => {
int length = ser.EndReceive(asyncResult);
Console.WriteLine(Encoding.UTF8.GetString(data));
},null);
}
public static void asyncSend(Socket client,string message) {
byte[] data = Encoding.UTF8.GetBytes(message);
client.BeginSend(data, 0, data.Length, SocketFlags.None, asyncResult => {
int length = client.EndSend(asyncResult);
Console.WriteLine("消息已发送");
},null);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
namespace ConsoleApplication12
{
class Program
{
static void Main(string[] args)
{
Socket Client = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
Client.BeginConnect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8000), asyncSesult => {
Client.EndConnect(asyncSesult);
Console.WriteLine("已连接服务器");
asyncSend(Client,"一号设备已连接");
asyncRecive(Client);
},null);
Console.Read();
}
public static void asyncRecive(Socket Ser) {
byte[] data=new byte[1024];
Ser.BeginReceive(data, 0, data.Length, SocketFlags.None,asyncResult => {
int length = Ser.EndReceive(asyncResult);
Console.WriteLine(Encoding.UTF8.GetString(data));
},null);
}
public static void asyncSend(Socket Ser,string message) {
byte[] data = Encoding.UTF8.GetBytes(message);
Ser.BeginSend(data, 0, data.Length, SocketFlags.None, asyncResult => {
int length = Ser.EndSend(asyncResult);
Console.WriteLine("消息已发送");
},null);
}
}
}
客户端