//提示,线程里面不要给控件赋值
LinkSocket.Send(result, length, 0);
自己挂起
private void button1_Click(object sender, EventArgs e)
{
bool ok = guaqi(IPAddress.Parse(rip.Text) ,int.Parse (rpont .Text ));
if (ok)
{
richTextBox1.Text = "挂起成功!";
jiantingkehuduan();//监听
}
else richTextBox1.Text = "挂起失败";
}
连接别人
private void button2_Click(object sender, EventArgs e)
{
bool ok = Link (IPAddress.Parse(rip.Text), int.Parse(rpont.Text));
if (ok)
{
richTextBox1.Text = "连接成功!";
clientSocket.Send(Encoding.UTF8.GetBytes("aaaaa"));
}
else richTextBox1.Text = "连接失败";
}
//CS************************************************
//定义
public int Pont;//端口
public IPAddress Ip;//ip
public Socket MySocket;//定义一个套接字
//挂起socket
public bool guaqi(IPAddress ip, int pont)
{
try //挂起socket,可以根据这个地方try一下判断启动服务器是否成功
{
Pont = pont;
Ip = ip;
MySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
MySocket.Bind(new IPEndPoint(Ip, Pont));
MySocket.Listen(30);//最多监听30个
return true;//挂起成功
}
catch
{
return false;//挂起失败
}
}
//监听客户端
public void jiantingkehuduan()
{
Thread myThread = new Thread(listen);
myThread.IsBackground = true;
myThread.Start();
}
//监听函数
public void listen()
{
while (true)
{
Socket now = MySocket.Accept();//监听到的这个赋值在p1ser..上
//每接收到一个连接就给他开一个单独的send便于交流
Thread tt = new Thread(send);//send是接收并发送消息
tt.IsBackground = true;
tt.Start(now);//建立一个和p1一起的发送接受线程
}
}
//send//接收和发送消息
public void send(object clientSocket)
{
Socket nowsocket = (Socket)clientSocket;
byte[] result = new byte[1024];
while (true)//一直和p1保持联系
{
try //可以try一下,catch的时候就是对方下线或者故障了
{
//接收******************
int len = nowsocket.Receive(result);//接收消息,并且存在result里
string tmp = Encoding.UTF8.GetString(result, 0, len);
//可以用if(tmp=="")来判断干什么
//发送**************
//nowsocket.Send(Encoding.UTF8.GetBytes("aaaaa"));
}
catch
{
return; //连接断开
}
}
}
//连接
Socket clientSocket;
public bool Link(IPAddress ip, int pont)
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
clientSocket.Connect(new IPEndPoint(ip, pont));
//int len = clientSocket.Receive(result);
//string tmp = Encoding.UTF8.GetString(result, 0, len);
return true;
}
catch
{
return false;
}
}