You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
86 lines
3.0 KiB
C#
86 lines
3.0 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Net;
|
|
using System.Net.Sockets;
|
|
using System.Threading;
|
|
|
|
namespace Mesnac.Communication
|
|
{
|
|
public class SyncSocketClient
|
|
{
|
|
private static SyncSocketClient instance = null;
|
|
/// <summary>
|
|
/// 客户端连接Socket
|
|
/// </summary>
|
|
private Socket clientSocket;
|
|
/// <summary>
|
|
/// 连接点
|
|
/// </summary>
|
|
private IPEndPoint hostEndPoint;
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
/// <param name="hostName">服务端地址{IP地址}</param>
|
|
/// <param name="port">端口号</param>
|
|
public SyncSocketClient(String hostName, Int32 port)
|
|
{
|
|
//IPHostEntry host = Dns.GetHostEntry(hostName);
|
|
//IPAddress[] addressList = host.AddressList;
|
|
//this.hostEndPoint = new IPEndPoint(addressList[addressList.Length - 1], port);
|
|
//this.clientSocket = new Socket(this.hostEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
|
|
}
|
|
/// <summary>
|
|
/// 连接服务端
|
|
/// </summary>
|
|
public string Send(String hostName, Int32 port, string message)
|
|
{
|
|
|
|
string receiveMsg = "";
|
|
IPHostEntry host = Dns.GetHostEntry(hostName);
|
|
IPAddress[] addressList = host.AddressList;
|
|
IPEndPoint hostPoint = new IPEndPoint(addressList[addressList.Length - 1], port);
|
|
using (clientSocket = new Socket(hostPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
|
|
{
|
|
|
|
clientSocket.Connect(hostPoint);
|
|
clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 5000);
|
|
byte[] sendMsg = Encoding.GetEncoding("GBK").GetBytes(message);
|
|
clientSocket.Send(sendMsg);
|
|
//设置超时
|
|
//clientSocket.ReceiveTimeout = 5000;
|
|
byte[] receiveByte = new byte[1024];
|
|
int count = 0;
|
|
try
|
|
{
|
|
count = clientSocket.Receive(receiveByte, receiveByte.Length, 0);//接受数据
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine(ex.Message + "接受信息超时!");
|
|
}
|
|
receiveMsg += Encoding.GetEncoding("GBK").GetString(receiveByte, 0, count);//转换为GBK格式的字符串
|
|
receiveMsg = receiveMsg.Replace("\n\r", "");
|
|
Console.WriteLine("接受信息:" + receiveMsg);
|
|
}
|
|
return receiveMsg;
|
|
}
|
|
|
|
/// <summary>
|
|
/// TCP通信服务实例
|
|
/// </summary>
|
|
public static SyncSocketClient Instance
|
|
{
|
|
get
|
|
{
|
|
if (instance == null)
|
|
{
|
|
instance = new SyncSocketClient("", 3666);
|
|
}
|
|
return instance;
|
|
}
|
|
}
|
|
}
|
|
}
|