C#套接字服务端程序
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace WindowsApplication3
{
public partial class Form1 : Form
{
private IPAddress myIp = IPAddress.Parse("127.0.0.1");
private IPEndPoint MyServer;
private Socket sock;
private bool check = true;
private Socket accSock;
private Thread th;
private delegate void myDel(string str);//----------声明控制所在线程的委托
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
myIp = IPAddress.Parse(textBox1.Text);
}
catch
{
MessageBox.Show("输入的IP格式不正确");
}
try
{
th = new Thread(new ThreadStart(accp));
th.Start();
}
catch (Exception ex)
{
textBox3.AppendText(ex.Message);
}
}
private void accp()
{
MyServer = new IPEndPoint(myIp, Int32.Parse(textBox2.Text));
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Bind(MyServer);
sock.Listen(50);
myDel del = new myDel(AddText);
textBox3.BeginInvoke(del, "主机:" + textBox1.Text + "端口:" + textBox2.Text + "开始监听。。。");
//不同线程对创建控件本身的线程的访问,使用委托
//调用拥有textbox3线程去执行
while (check)
{
accSock = sock.Accept();
if (accSock.Connected)
{
textBox3.BeginInvoke(del,"已经建立连接");
byte[] getByte = new byte[64];
NetworkStream netStream = new NetworkStream(accSock);
netStream.Read(getByte, 0, getByte.Length);
string getStr = Encoding.BigEndianUnicode.GetString(getByte);
Thread.Sleep(1500);
richTextBox1.AppendText(getStr + "/r/n");
}
}
}
private void button3_Click(object sender, EventArgs e)
{
try
{
th.Abort();
//不加这一句,会导致一个封锁操作被对 WSACancelBlockingCall 的调用中断。异常。
//因为你使用了多线程,关掉了端口,然而一个线程还在工作,在访问这个端口,结果报错。
//关所有线程。Abort();
sock.Close();
richTextBox1.AppendText("主机:" + textBox1.Text + "端口:" + textBox2.Text + "停止监听");
}
catch
{
MessageBox.Show("监听还未开始,无法关闭");
}
}
private void AddText(string str)
{
textBox3.AppendText(str);
}
private void button2_Click(object sender, EventArgs e)
{
try
{
byte[] sendByte = new byte[64];
string sendStr = richTextBox2.Text + "/r/n";
sendByte = Encoding.BigEndianUnicode.GetBytes(sendStr);
NetworkStream netStream = new NetworkStream(accSock);
netStream.Write(sendByte,0,sendByte.Length);
}
catch
{
MessageBox.Show("连接未来建立,无法发送消息");
}
}
}
}