using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
namespace Control
{
public class SocketHepler
{
SocketHepler()
{
}
#region 拍照socket
//创建连接的Socket
//public static Socket socketSend;
public static void Connect()
{
try
{
string host = Global.host;// ConfigurationManager.AppSettings["socket_host"];
string port = Global.port;// ConfigurationManager.AppSettings["socket_port"];
Global.socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse(host); //获取ip地址.
Global.socketSend.Connect(ip, Convert.ToInt32(port));
//连接成功,就可以接收服务器发送的信息了.
//Thread th = new Thread(ReceiveMsg);
//th.Start();
}
catch (Exception ex)
{
MessageBox.Show("连接服务器出错:" + ex.ToString());
}
}
//接收服务器的消息.
public static void ReceiveMsg()
{
while (true)
{
try
{
byte[] buffer = new byte[1024 * 1024];
int len = Global.socketSend.Receive(buffer); //获取长度
string mes = Encoding.UTF8.GetString(buffer, 0, len);
Global.ReceiveMsg(mes);
}
catch (Exception ex)
{
MessageBox.Show("ReceiveMsg出错:" + ex.ToString());
break;
}
}
}
public static string Send(string mes)
{
pubfunction.WriteLogWorkDate_n("socketSend", mes);
string res = "";
//客户端发服务器消息.
if (Global.socketSend != null)
{
try
{
//断开重连
if (!Global.socketSend.Connected)
{
pubfunction.WriteLogWorkDate_n("socketSend", "断开重连");
Connect();
pubfunction.WriteLogWorkDate_n("socketSend", "重连成功");
}
//发送消息.
//showMsg(txtMsg.Text);
byte[] buffern = Encoding.UTF8.GetBytes(mes);
Global.socketSend.Send(buffern);
pubfunction.WriteLogWorkDate_n("socketSend", "发送成功");
while (res == "")
{
try
{
byte[] buffer = new byte[1024 * 1024];
int len = Global.socketSend.Receive(buffer); //获取长度
res = Encoding.UTF8.GetString(buffer, 0, len);
//Global.ReceiveMsg(mes);
}
catch (Exception ex)
{
MessageBox.Show("ReceiveMsg出错:" + ex.ToString());
break;
}
}
}
catch (Exception ex)
{
pubfunction.WriteLogWorkDate_n("socketSend", ex.ToString());
//显示出错的消息
MessageBox.Show("Send出错的消息:" + ex.ToString());
}
}
pubfunction.WriteLogWorkDate_n("socketSend", "结果:" + res);
return res;
}
#endregion
}
}
C# socket操作类
最新推荐文章于 2023-11-11 11:35:50 发布