using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
namespace ClientSocket
{
public class ClientHandle
{
private string ip;
private int port;
private Socket clientSocket;
private byte[] byteBuffer;
private bool socketState = false;
/// <summary>
/// ip
/// </summary>
public string IP { get; set; }
/// <summary>
/// 端口号
/// </summary>
public int Port { get; set; }
/// <summary>
/// 客户端socket
/// </summary>
public Socket ClientSocket { get; set; }
/// <summary>
/// 构造方法
/// </summary>
/// <param name="ip">ip地址</param>
/// <param name="port">端口号</param>
public ClientHandle(string ip, int port)
{
this.ip = ip;
this.port = port;
}
/// <summary>
/// 开启客户端
/// </summary>
/// <param name="clientSocket">客户端的socket</param>
/// <param name="ip">客户端的ip</param>
/// <param name="port">端口号</param>
public void StartClient()
{
//创建客户端socket对象
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//创建ip对象
IPAddress address = IPAddress.Parse(ip);
//创建端口对象
IPEndPoint endPoint = new IPEndPoint(address, port);
//异步方法连接服务端
clientSocket.BeginConnect(endPoint, new AsyncCallback(ConnectHandler), clientSocket);
//初始化字节数组
byteBuffer = new byte[clientSocket.ReceiveBufferSize];
try
{
clientSocket.BeginReceive(byteBuffer, 0, byteBuffer.Length, 0,
new AsyncCallback(ReceiveHandler), clientSocket);
}
catch (Exception)
{
Console.WriteLine("收不到服务端的消息");
}
}
/// <summary>
/// 处理客户端连接服务器
/// </summary>
/// <param name="asyncResult">客户端的socket</param>
private void ConnectHandler(IAsyncResult asyncResult)
{
Socket clientSocket = (Socket)asyncResult.AsyncState;
if (clientSocket.Connected)
{
Console.WriteLine($"客户端{clientSocket.LocalEndPoint.ToString()}连接服务器端成功.");
socketState = true;
clientSocket.EndConnect(asyncResult);
}
else
{
Console.WriteLine("客户端连接服务器端失败.");
}
}
/// <summary>
/// 接收到服务器端发送过来的消息之后的回调方法.
/// </summary>
/// <param name="asyncResult"></param>
private void ReceiveHandler(IAsyncResult asyncResult)
{
Socket clientSocket = (Socket)asyncResult.AsyncState;
try
{
int count = clientSocket.EndReceive(asyncResult);
if (count == 0)
{
Console.WriteLine("长度为0.");
return;
}
//转码成字符串.
string str = Encoding.UTF8.GetString(byteBuffer, 0, count);
Console.WriteLine(str);
}
catch (Exception)
{
Console.WriteLine("服务端已关闭");
}
//重置字节数组.
byteBuffer = new byte[clientSocket.ReceiveBufferSize];
//接收下一条数据.
try
{
clientSocket.BeginReceive(byteBuffer, 0, byteBuffer.Length, 0,
new AsyncCallback(ReceiveHandler), clientSocket);
}
catch (Exception)
{
Console.WriteLine("服务端已关闭");
}
}
/// <summary>
/// 发送消息至服务端
/// </summary>
/// <param name="text">消息内容</param>
public void SendMsgToServer(string text)
{
if (socketState == false) return;
byte[] message = Encoding.UTF8.GetBytes(text);
try
{
clientSocket.BeginSend(message, 0, message.Length, 0, new AsyncCallback(SendHandler), clientSocket);
}
catch (Exception)
{
Console.WriteLine("消息发送失败");
}
}
/// <summary>
/// 消息发送成功之后的回调方法.
/// </summary>
/// <param name="asyncResult"></param>
private static void SendHandler(IAsyncResult asyncResult)
{
Socket socket = (Socket)asyncResult.AsyncState;
int count = socket.EndSend(asyncResult);
Console.WriteLine("消息发送成功,长度为:" + count);
}
/// <summary>
/// 关闭客户端
/// </summary>
/// <param name="socket"></param>
public void CloseClient()
{
socketState = false;
clientSocket.Close();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
namespace ClientSocket
{
internal class Program
{
static void Main(string[] args)
{
string ip = "127.0.0.1";
int port = 8885;
int arrayLength = 1024;
ClientHandle clientHandle = new ClientHandle(ip, port);
clientHandle.StartClient();
while (true)
{
string str = Console.ReadLine();
clientHandle.SendMsgToServer(str);
}
Console.ReadKey();
}
}
}