using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; namespace HHWMS.Web { public class SyncSocketClient { private static SyncSocketClient instance = null; /// /// 客户端连接Socket /// private Socket clientSocket; /// /// 连接点 /// private IPEndPoint hostEndPoint; /// /// /// /// 服务端地址{IP地址} /// 端口号 public SyncSocketClient(String hostName, Int32 port) { //IPAddress address = null; //if (!String.IsNullOrEmpty(hostName)) //{ // IPAddress.TryParse(hostName, out address); //} //else //{ // IPHostEntry host = Dns.GetHostEntry(hostName); // IPAddress[] addressList = host.AddressList; // foreach (IPAddress ad in addressList) // { // if (ad.AddressFamily == AddressFamily.InterNetwork) // { // address = ad; // break; // } // } //} //this.hostEndPoint = new IPEndPoint(address, port); //this.clientSocket = new Socket(this.hostEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); } /// /// 连接服务端 /// public string Send(String hostName, Int32 port, string message) { string receiveMsg = ""; IPAddress address = null; if (!String.IsNullOrEmpty(hostName)) { IPAddress.TryParse(hostName, out address); } else { IPHostEntry host = Dns.GetHostEntry(hostName); IPAddress[] addressList = host.AddressList; foreach (IPAddress ad in addressList) { if (ad.AddressFamily == AddressFamily.InterNetwork) { address = ad; break; } } } IPEndPoint hostPoint = new IPEndPoint(address, 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; } /// /// TCP通信服务实例 /// public static SyncSocketClient Instance { get { if (instance == null) { instance = new SyncSocketClient("", 3666); } return instance; } } } }