服务器端程序
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace SocketServer
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
//定义端口号
private const int porNum=81;
[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此处添加代码以启动应用程序
//
bool done=false;
TcpListener listener=new TcpListener(porNum);
listener.Start();
while(!done){
Console.Write("正在侦听81端口...");
TcpClient client=listener.AcceptTcpClient();
Console.WriteLine("\n处理连接请求...");
NetworkStream ns=client.GetStream();
//ns.Read(,0,);
byte[] bytes=new byte[1024];
int bytesRead=ns.Read(bytes,0,bytes.Length);
Console.WriteLine(Encoding.BigEndianUnicode.GetString(bytes,0,bytesRead));
byte[] byteTime=Encoding.ASCII.GetBytes(DateTime.Now.ToString());
try
{
ns.Write(byteTime,0,byteTime.Length);
ns.Close();
client.Close();
}
catch(Exception ex){
Console.WriteLine(ex.ToString());
}
}
listener.Stop();
}
}
}
Web客户端
添加命名空间:
using System.Net;
using System.Net.Sockets;
using System.Text;
连接代码:
private void socketButton_Click(object sender, System.EventArgs e)
{//连接服务器程式
try
{
//开始连接
TcpClient client=new TcpClient("192.168.0.100",81);
NetworkStream ns=client.GetStream();
byte[] byteTime=Encoding.BigEndianUnicode.GetBytes("客户端数据提交\n");
ns.Write(byteTime,0,byteTime.Length);
//返回客户端信息
byte[] clientIp=Encoding.BigEndianUnicode.GetBytes("客户端IP地址:"+Request.UserHostAddress+"\n");
ns.Write(clientIp,0,clientIp.Length);
byte[] bytes=new byte[1024];
int bytesRead=ns.Read(bytes,0,bytes.Length);
showLabel.Text="服务器返回信息"+Encoding.ASCII.GetString(bytes,0,bytesRead);
client.Close();
}
catch(Exception ex)
{
showLabel.Text="抛出异常"+ex.ToString();
}
finally{}
}