110,533
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 使用Socket的tcp通讯
/// </summary>
/// <param name="SendText">要发送的字符串</param>
/// <returns></returns>
public string CommunicteSocketTcp(string SendText)
{
Byte[] ByteGet = ASCIIEncoding.ASCII.GetBytes(SendText);
Socket s = null;
try
{
IPAddress hostAddress = IPAddress.Parse("192.168.1.50");
int conPort = 80;
IPEndPoint hostEndPoint = new IPEndPoint(hostAddress, conPort);
//Create The Socket to send data over a tcp connection
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//Connect to the host using its IPEndPoint.
s.Connect(hostEndPoint);
if (!s.Connected)
{
s.Close();
s = null;
throw new Exception("连接不成功");
}
//Sent the GET request to the host.
s.Send(ByteGet, ByteGet.Length, 0);
byte[] recvBytes = new byte[1024];
int bytes = s.Receive(recvBytes, recvBytes.Length, 0);//从
s.Close();
}
catch (Exception eee)
{
if (s != null)
{
s.Close();
}
return eee.Message;
}
return "读取成功";
}