usingSystem;usingSystem.Text;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;usingSystem.Net;usingSystem.Net.Sockets;usingSystem.Threading;usingSystem.IO;namespacewin2web_web
{public partial classwelcome : System.Web.UI.Page
{static int count = 0;private Socket s; //定义Socket对象
private Thread th; //客户端连接服务器的线程
public Socket cSocket; //单个客户端连接的Socket对象
public NetworkStream ns; //网络流
public StreamReader sr; //流读取
public StreamWriter sw; //流写入
private delegate void SetTextCallback(); //用于操作主线程控件
protected string dispaly { get; set; }protected void Page_Load(objectsender, EventArgs e)
{
}protected void bt_start_Click(objectsender, EventArgs e)
{
bt_start.Enabled= false;
s= newSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress serverIP= IPAddress.Parse(“115.156.186.55”);
IPEndPoint server= new IPEndPoint(serverIP, 1737);
s.Bind(server);
s.Listen(10);try{
th= new Thread(newThreadStart(Communication));
th.Start();
lblConnet.Text= “服务器启动成功!”;
}catch(Exception ex)
{
lblError.Text= “服务器启动失败!” +ex.Message;
}
}public voidCommunication()
{while (true)
{try{
cSocket= s.Accept(); //用cSocket来代表该客户端连接
if (cSocket.Connected) //测试是否连接成功
{
ns= new NetworkStream(cSocket);//建立网络流,便于数据的读取
sr = new StreamReader(ns); //实例化流读取对象
sw = new StreamWriter(ns); //实例化写入流对象
test(); //从流中读取
sw.WriteLine(“收到请求,允许连接”); //向流中写入数据
sw.Flush(); //清理缓冲区
}else{
lblError.Text= “连接失败”;
}
}catch(SocketException ex)
{
lblError.Text= ex.Message; //捕获Socket异常
}catch(Exception es)
{
lblError.Text= “其它异常” + es.Message; //捕获其他异常
}
}
}public voidsend()
{
lbInfo.Items.Add(sr.ReadLine()+ “\n”);
}public voidtest()
{
SetTextCallback stcb= newSetTextCallback(send);//Invoke(stcb);
dispaly =sr.ReadLine();//lblSend.Text = dispaly;
lblSend.Text = “123456”;//问题就是这个语句给控件Label直接赋值都不能在前端显示?怎么解决
}protected void btnClose_Click(objectsender, EventArgs e)
{//s_Sock.Close();
s.Close();
}protected void OnTimeTick(objectsender, EventArgs e)
{
count++;if (count > 10)
count= 0;
tbDisplay.Text= “–” +count.ToString();
}
}
}