Sockets客户端TCP
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
class SocketTcpClick
{
Socket socketClient;
Thread threadClient;
string senddata;
bool connectBool=false; //连接状态
/// <summary>
/// 发送消息
/// </summary>
/// <param name="senddata"></param>
public void Senddata(string senddata)
{
try
{
if (socketClient.Connected)
{
byte[] buffer = Encoding.GetEncoding("GBK").GetBytes(senddata);
socketClient.Send(buffer);
}
else
{
connectBool = false;
Console.WriteLine("连接失败");
}
}
catch (Exception)
{
Console.WriteLine("连接失败");
}
}
/// <summary>
/// 开启服务器连接
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void SocketStartClick(string ip,int port)
{
try
{
socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socketClient.Connect(ip, port);
threadClient = new Thread(RecMsg);
threadClient.IsBackground = true;
connectBool = socketClient.Connected;
Thread.Sleep(800);
threadClient.Start();
}
catch (Exception e)
{
connectBool = false;
}
}
/// <summary>
/// 接受消息
/// </summary>
private void RecMsg()
{
while (true) //持续监听服务端发来的消息
{
//定义一个1024*200的内存缓冲区 用于临时性存储接收到的信息
byte[] buffer = new byte[1024 * 200];
//将客户端套接字接收到的数据存入内存缓冲区, 并获取其长度
int length = socketClient.Receive(buffer);
if (length == 0)
{
break;
}
else
{
string str = Encoding.GetEncoding("GBK").GetString(buffer, 0, length - 1); //修改为GBK转码
senddata = str;
//string str = Encoding.Default.GetString(buffer, 1, length - 1);
Console.WriteLine("接受到服务器消息#", str);
Senddata(str);
}
}
}
public void Close()
{
try
{
socketClient.Close();
}
catch (Exception)
{
Console.WriteLine("Close#");
}
}
}