using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
namespace win2web_web
{
public partial class welcome : 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(object sender, EventArgs e)
{
}
protected void bt_start_Click(object sender, EventArgs e)
{
bt_start.Enabled = false;
s = new Socket(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(new ThreadStart(Communication));
th.Start();
lblConnet.Text = "服务器启动成功!";
}
catch (Exception ex)
{
lblError.Text = "服务器启动失败!" + ex.Message;
}
}
public void Communication()
{
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 void send()
{
lbInfo.Items.Add(sr.ReadLine() + "\n");
}
public void test()
{
SetTextCallback stcb = new SetTextCallback(send);
//Invoke(stcb);
dispaly = sr.ReadLine();
//lblSend.Text = dispaly;
lblSend.Text = "123456";
//问题就是这个语句给控件Label直接赋值都不能在前端显示?怎么解决
}
protected void btnClose_Click(object sender, EventArgs e)
{
//s_Sock.Close();
s.Close();
}
protected void OnTimeTick(object sender, EventArgs e)
{
count++;
if (count > 10)
count = 0;
tbDisplay.Text = "--" + count.ToString();
}
}
}
在.aspx文件中 label语句如下:
<asp:Label ID="lblSend" runat="server" Text=<%#dispaly %>></asp:Label>
希望各路大神不吝赐教!