1、C#socket
using System.Net;
using System.Net.Sockets;
using System.Threading;
public string Connect_Server(string IP, string Port, out int re)
{
IPAddress ip = IPAddress.Parse(IP);
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
clientSocket.Connect(new IPEndPoint(ip, Int32.Parse(Port)));
re = 0;
return "Connect Success";
}
catch
{
re = 1;
return "Connect Fail";
}
}
public string Receive()
{
byte[] result = new byte[1024];
clientSocket.Receive(result);
return System.Text.Encoding.Default.GetString(result);
}
public void SendData(string data)
{
clientSocket.Send(Encoding.ASCII.GetBytes(data));
}
2、多线程
using System.Threading;
Control.CheckForIllegalCrossThreadCalls = false; //c#控件是非线程安全的,多线程设置控件属性的时候,调试状态会报错InvalidOperationException,添加此语句可以忽略此错误
//线程启动
Thread thread_rec thread_rec = new Thread(new ThreadStart(ThreadFunc));
thread_rec.Start();
//多线程中启动窗体
private void ThreadFunc()
{
MethodInvoker mi = new MethodInvoker(this.Wait_Receive);
this.BeginInvoke(mi);
}
public void Wait_Receive()
{
while (true)
{
//
}
Login login = new Login(re_socket);
login.Show();
this.Hide();
}
3.定时器
System.Threading.Timer timer = new System.Threading.Timer(new TimerCallback(Tick), null, 3000, 3000);
void Tick(object data)
{
if (!receive_sig)
{
label_connectInfo.Text = "receive string timeout";
button_connect.Enabled = true;
receive_sig = true;
Application.DoEvents();
thread_rec.Interrupt();
}
timer.Dispose();
}