110,536
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
#region 私有成员变量
private static ILog log = LogManager.GetLogger(typeof(Frmain));
//private static int port = 2323;
private static int port = 1521;
private static ManualResetEvent receiveDone = new ManualResetEvent(false);
private static Thread ReviceThread;
private static Thread KeepAliveThread;
private static object obj = new object();
private static string MessageSN = "0";
private static IPAddress ipAddress;
string str = "192.168.96.1";
string str_ip;
#endregion
#region 公有成员变量
public static DateTime tempDate = DateTime.Now;
public static Socket client;
public static bool isNeedAlive = true;
StateObject state = new StateObject();
#endregion
public Frmain()
{
InitializeComponent();
StartClient();
}
/// <summary>
/// 启动客户端
/// </summary>
private void StartClient()
{
try
{
ipAddress = IPAddress.Parse(str);
ConnnectServer();
StartSendServer();
RunReceive();
// RunKeepAlive();
}
catch (Exception e)
{
MessageBox.Show(e.Message );
log.Error(e.Message.ToString());
str_ip = string.Empty;
}
}
/// <summary>0
/// 连接服务器
/// </summary>
public void ConnnectServer()
{
try
{
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);//定义主机对象
client = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
client.BeginConnect(remoteEP,new AsyncCallback(ConnectCallback), client);
}
catch (Exception e)
{
log.Error(e.Message.ToString());
}
}
……
/// 接受服务回调
/// </summary>
private void ReceiveCallback(IAsyncResult ar)
{
StateObject state = (StateObject)ar.AsyncState;//从输入参数异步state对象中获取state和socket对象
Socket handler = state.workSocket;
try
{
int bytesRead = client.EndReceive(ar);//从远端设备读取数据,此处没有读到信息
if (bytesRead > 0)
{
AnalysisData(Encoding.Default.GetString(state.buffer, 0, bytesRead), handler);
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
}
}
catch (Exception e)
{
// Console.WriteLine(e.ToString());
// MessageBox.Show(e.Message);
if (handler.Connected)
{
handler.Shutdown(SocketShutdown.Both);
handler.BeginDisconnect(false, new AsyncCallback(BeginDisconnectCallback), state);
}
log.Error(e.Message.ToString());
}
}
/// <summary>
/// 接受断开回调
/// </summary>
private static void BeginDisconnectCallback(IAsyncResult ar)//接收来自服务端的返回确认信息
{
try
{
StateObject state = (StateObject)ar.AsyncState;
state.workSocket.EndDisconnect(ar);
}
catch
{
Socket socket = (Socket)ar.AsyncState;
socket.EndDisconnect(ar);
}
}
private void AnalysisData(string recv, Socket handler)
{
try
{
//Control.CheckForIllegalCrossThreadCalls = false;
// AlertCustom alert = new AlertCustom(recv);
// alert.Show();
// Thread secondThread = new Thread(alert.Show);
// secondThread.Start();
this.Invoke(new ThreadStart(delegate()
{
AlertCustom alert = new AlertCustom(recv);
alert.CaptionText = "即时信息平台";
alert.Show(this);
}));
// MessageBox.Show(recv);
}
catch (Exception e)
{
log.Error(e.Message.ToString());
}
finally
{
// Dispose();
}
}