简单Socket-Tcp通信
在本文中涉及到通信,仅做简单的通信(服务端接受消息,由客户端发出消息)
如有需要,根据需求可直接copy使用
关键字Socket
需要引用命名空间:
using System.Net;
using System.Net.Sockets;
服务端:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Socket_TcpServer
{
class Program
{
static void Main(string[] args)
{
SocketStart();
}
public static byte[] clientMsg = new byte[340];
/// <summary>
/// 开启TCP通信
/// </summary>
/// <param name="o"></param>
private static void SocketStart()
{
int localPort = 8345;
Socket[] ClientSocket; //为客户端建立的SOCKET连接
Socket socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socketServer.Bind(new IPEndPoint(IPAddress.Any, localPort)); //将服务端绑定本地端口号
socketServer.Listen(10); //10 表示最大连接数
Console.WriteLine("------服务端开启------");
ClientSocket = new Socket[65535];
int ClientNumb = 0;
while (true)
{
ClientSocket[ClientNumb] = socketServer.Accept();
Console.WriteLine("-----SOCKET客户端接入-----");
ClientSocket[ClientNumb].BeginReceive(clientMsg, 0, clientMsg.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack1), ClientSocket[ClientNumb]);
ClientNumb++;
}
}
/// <summary>
/// 接受通信数据
/// </summary>
/// <param name="AR"></param>
public static void ReceiveCallBack1(IAsyncResult AR)
{
Socket socket = (Socket)AR.AsyncState;
try
{
int endREC = clientMsg.Length;
string content = Encoding.GetEncoding("GBK").GetString(clientMsg, 0, endREC); //将接收到的数据进行转码
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss")+"收到客户端"+socket.RemoteEndPoint + "消息 \r\n{0}"+content);
clientMsg = new byte[clientMsg.Length];
socket.BeginReceive(clientMsg, 0, clientMsg.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack1), socket); //运用递归方式重新接收新的数据
}
catch (Exception ex)
{
//Console.WriteLine(ex.ToString());
Console.WriteLine("--客户端 "+socket.RemoteEndPoint+" 连接断开-----");
}
}
}
}
客户端:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Socket_TcpClient
{
class Program
{
static void Main(string[] args)
{
string content = "这个测试用的一个TCP连接";
Socket(content); //开启socket通信
Console.ReadKey();
}
static void Socket(string content)
{
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.Bind(new IPEndPoint(IPAddress.Any, 21310)); //将客户端端绑定本地端口号
int remotePort = 8345;
IPAddress remoteIP = IPAddress.Parse("192.168.11.83");
IPEndPoint remoteIPEndPoint = new IPEndPoint(remoteIP, remotePort); //绑定需要连接的远端服务器端口号
clientSocket.Connect(remoteIPEndPoint);
try
{
byte[] sendBytes = Encoding.ASCII.GetBytes(content);
clientSocket.Send(sendBytes);
Console.WriteLine("发送成功!");
}
catch
{
Console.WriteLine("发送失败!");
}
}
}
}