//client
public class ClientSide : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button btnGet;
private const int portNum = 13;//服务器端口,可以随意修改
private const string hostName = "127.0.0.1";//服务器地址,127.0.0.1指本机
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.btnGet.Click += new System.EventHandler(this.btnGet_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void btnGet_Click(object sender, System.EventArgs e)
{
try
{
Response.Write("Try to connect to "+hostName+":"+portNum.ToString()+"<br>");
TcpClient client = new TcpClient(hostName, portNum);
NetworkStream ns = client.GetStream();
byte[] bytes = new byte[1024];
int bytesRead = ns.Read(bytes, 0, bytes.Length);
Response.Write(Encoding.ASCII.GetString(bytes,0,bytesRead));
client.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
}
}
}
}
Server
public class ServerSide : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button btnStart;
private const int portNum = 13;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void btnStart_Click(object sender, System.EventArgs e)
{
bool done = false;
TcpListener listener = new TcpListener(portNum);
listener.Start();
while (!done)
{
Response.Write("Waiting for connection...");
TcpClient client = listener.AcceptTcpClient();
Response.Write("Connection accepted.");
NetworkStream ns = client.GetStream();
byte[] byteTime = Encoding.ASCII.GetBytes(DateTime.Now.ToString());
try
{
ns.Write(byteTime, 0, byteTime.Length);
ns.Close();
client.Close();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
listener.Stop();
}
}
}