如果你只想这样,那么我建议你用tcpclient,它封装了socket,用起来更简单 客户端: tcpclient = new TcpClient(); tcpclient.Connect("192.168.1.64", 8888); 接受数据 NetworkStream network=tcpclient.GetStream(); byte[] send = new byte[1024]; int number = network.Read(send, 0, send.Length); 服务器端: 创建两个线程,一个用于监听,一个用与处理事件
引用: using System.Net.Sockets; 服务器端: public static string data = null; //启动监听 public static void StartListening() { // Data buffer for incoming data. //字节数组用来接收数据 byte[] bytes = new Byte[1024]; // Establish the local endpoint for the socket. //为Socket设置本地端口 // Dns.GetHostName returns the name of the // host running the application. //通过Dns.GetHostName获得主机名 IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); //将 DNS 主机名或 IP 地址解析为 IPHostEntry 实例。 //IPHostEntry用于为 Internet 主机地址信息提供容器类。 IPAddress ipAddress = ipHostInfo.AddressList[0]; //ip地址 IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);//IPEndPoint 用于将网络端点表示为 IP 地址和端口号。 // Create a TCP/IP socket. //创建一个基于TCP/IP协议的Socket Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Bind the socket to the local endpoint and // listen for incoming connections. //将Socket与本地端口绑定,监听请求的连接 try { listener.Bind(localEndPoint); listener.Listen(10); //将Socket设置为监听状态,参数为挂起连接队列的最大长度 // Start listening for connections. //为连接开启监听 while (true) { Console.WriteLine("Waiting for a connection..."); //Program is suspended while waiting for an incoming connection. //Accept 以同步方式从侦听套接字的连接请求队列中提取第一个挂起的连接请求,然后创建并返回新的 Socket Socket handler = listener.Accept(); data = null; // An incoming connection needs to be processed. while (true) { bytes = new byte[1024]; int bytesRec = handler.Receive(bytes); data += Encoding.ASCII.GetString(bytes, 0, bytesRec); if (data.IndexOf("<EOF>") > -1) { break; } } // Show the data on the console. Console.WriteLine("Text received : {0}", data); // Echo the data back to the client. byte[] msg = Encoding.ASCII.GetBytes(data); handler.Send(msg); handler.Shutdown(SocketShutdown.Both); handler.Close(); } } catch (Exception e) { Console.WriteLine(e.ToString()); } Console.WriteLine("\nPress ENTER to continue..."); Console.Read(); }客户端: // Data buffer for incoming data. byte[] bytes = new byte[1024]; // Connect to a remote device. try { // Establish the remote endpoint for the socket. // This example uses port 11000 on the local computer. IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); IPAddress ipAddress = ipHostInfo.AddressList[0]; //IPEndPoint remoteEP = new IPEndPoint(ipAddress,11000); IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("192.168.1.221"),1001); // Create a TCP/IP socket. Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); // Connect the socket to the remote endpoint. Catch any errors. try { sender.Connect(remoteEP); Console.WriteLine("Socket connected to {0}", sender.RemoteEndPoint.ToString()); Console.WriteLine("ok"); // Encode the data string into a byte array. //将字符串转化为字节数组传送给服务器端 byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>"); //byte[] msg = Encoding.ASCII.GetBytes("01 03 01 01 00 01 D4 36"); // Send the data through the socket. int bytesSent = sender.Send(msg); // Receive the response from the remote device. int bytesRec = sender.Receive(bytes); Console.WriteLine("Receive"); Console.WriteLine("Echoed test = {0}", Encoding.ASCII.GetString(bytes,0,bytesRec)); // Release the socket. //sender.Shutdown(SocketShutdown.Both); //sender.Close();
客户端:
tcpclient = new TcpClient();
tcpclient.Connect("192.168.1.64", 8888);
接受数据
NetworkStream network=tcpclient.GetStream();
byte[] send = new byte[1024];
int number = network.Read(send, 0, send.Length);
服务器端:
创建两个线程,一个用于监听,一个用与处理事件
using System.Net.Sockets;
服务器端:
public static string data = null; //启动监听
public static void StartListening()
{
// Data buffer for incoming data.
//字节数组用来接收数据
byte[] bytes = new Byte[1024]; // Establish the local endpoint for the socket.
//为Socket设置本地端口
// Dns.GetHostName returns the name of the
// host running the application.
//通过Dns.GetHostName获得主机名
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); //将 DNS 主机名或 IP 地址解析为 IPHostEntry 实例。
//IPHostEntry用于为 Internet 主机地址信息提供容器类。
IPAddress ipAddress = ipHostInfo.AddressList[0]; //ip地址
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);//IPEndPoint 用于将网络端点表示为 IP 地址和端口号。 // Create a TCP/IP socket.
//创建一个基于TCP/IP协议的Socket
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp); // Bind the socket to the local endpoint and
// listen for incoming connections.
//将Socket与本地端口绑定,监听请求的连接
try
{
listener.Bind(localEndPoint);
listener.Listen(10); //将Socket设置为监听状态,参数为挂起连接队列的最大长度 // Start listening for connections.
//为连接开启监听
while (true)
{
Console.WriteLine("Waiting for a connection...");
//Program is suspended while waiting for an incoming connection.
//Accept 以同步方式从侦听套接字的连接请求队列中提取第一个挂起的连接请求,然后创建并返回新的 Socket
Socket handler = listener.Accept();
data = null; // An incoming connection needs to be processed.
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<EOF>") > -1)
{
break;
}
} // Show the data on the console.
Console.WriteLine("Text received : {0}", data); // Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes(data); handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
} }
catch (Exception e)
{
Console.WriteLine(e.ToString());
} Console.WriteLine("\nPress ENTER to continue...");
Console.Read(); }客户端:
// Data buffer for incoming data.
byte[] bytes = new byte[1024]; // Connect to a remote device.
try {
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
//IPEndPoint remoteEP = new IPEndPoint(ipAddress,11000);
IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("192.168.1.221"),1001); // Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp ); // Connect the socket to the remote endpoint. Catch any errors.
try {
sender.Connect(remoteEP); Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString()); Console.WriteLine("ok"); // Encode the data string into a byte array.
//将字符串转化为字节数组传送给服务器端
byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");
//byte[] msg = Encoding.ASCII.GetBytes("01 03 01 01 00 01 D4 36"); // Send the data through the socket.
int bytesSent = sender.Send(msg); // Receive the response from the remote device.
int bytesRec = sender.Receive(bytes); Console.WriteLine("Receive"); Console.WriteLine("Echoed test = {0}",
Encoding.ASCII.GetString(bytes,0,bytesRec)); // Release the socket. //sender.Shutdown(SocketShutdown.Both);
//sender.Close();
} catch (ArgumentNullException ane) {
Console.WriteLine("ArgumentNullException : {0}",ane.ToString());
} catch (SocketException se) {
Console.WriteLine("SocketException : {0}",se.ToString());
} catch (Exception e) {
Console.WriteLine("Unexpected exception : {0}", e.ToString());
} } catch (Exception e) {
Console.WriteLine( e.ToString());
}服务器和客户端代码差不多,主要区别在于服务器处于监听,客户端发连接请求,在套接字绑定IP是绑定的服务器IP你的思路只需要要在服务器接受数据的函数里做判断,判断客户端是否发送了规定的数据,转而做你定义的事情,在把信息回馈给客户端。
这个例子程序在服务器端的信息是用XML存储的,当然也可以用数据库,XML文档也比较简单,我只是想看下这个思想是否可行.
1、XML文档结构(服务器端用于存储软件验证信息)
<?XML Version=”1.0”>
<soft>
<softname>软件名</softname>
<softinfo>验证信息</softinfo>
</soft>
2、服务器对验证信息的处理程序
//SOCKET套接字在C#中定义在System.Net.Sockets命名空间
//服务器端接收验证信息处理程序
static void TCPServer()
{
int port = 2000;
string host = "127.0.0.1";
/**////创建终结点(EndPoint)
IPAddress ip = IPAddress.Parse(host);
//用指定的端口和ip初始化IPEndPoint类的新实例
IPEndPoint ipe = new IPEndPoint(ip, port);
/**////创建socket并开始监听
Socket s=new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
s.Bind(ipe);//绑定EndPoint对像(2000端口和ip地址)
s.Listen(0);//开始监听
Console.WriteLine("等待客户端连接");
/**////接受到client连接,为此连接建立新的socket,并接受信息
Socket temp = s.Accept();//为新建连接创建新的socket
Console.WriteLine("建立连接");
string recvStr = "";
byte[] recvBytes = new byte[1024];
int bytes;
bytes = temp.Receive(recvBytes, recvBytes.Length, 0);//从客户端接受信息
recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
/**////给client端返回信息
//处理接收到的数据
String XmlStr=””;//定义存储从XML文档中读取的数据
Sting Info;//定义返回客户端的数据
//读服务器XML文档处理
XmlTextReader Reader=new XMLTextReader(“服务器的XML文档”);
//开始读XML文档
While(Reader.Read())
{
if(reader.NodeType== XMLNodeType.Element)
{
If(Reader.Name==”softname”)
XmlStr+=”softname=”;
If(Reader.Name==”softinfo”)
XmlStr+=”softinfo=”;
}
If(reader.NodeType== XMLNodeType.Text)
XmlStr+=Reader.Value;
}
If(XmlStr==recvStr) Info=”true”;
Else Info=”false”;
string sendStr = Info;
byte[] bs = Encoding.ASCII.GetBytes(sendStr);
temp.Send(bs, bs.Length, 0);//返回信息给客户端
temp.Close();
s.Close();
Console.ReadLine();
}
3、用户发送验证信息示例程序
static void TCPClient(string[] args)
{
try
{
int port = 2000;
string host = "127.0.0.1";
/**////创建终结点EndPoint
IPAddress ip = IPAddress.Parse(host);
//IPAddress ipp = new IPAddress("127.0.0.1");
//把ip和端口转化为IPEndpoint实例
IPEndPoint ipe = new IPEndPoint(ip, port); /**////创建socket并连接到服务器
Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建Socket
Console.WriteLine("Conneting…");
c.Connect(ipe);//连接到服务器 /**////向服务器发送信息
string sendStr = "softname=软件名softinfo=验证信息";
byte[] bs = Encoding.ASCII.GetBytes(sendStr);//把字符串编码为字节
Console.WriteLine("Send Message");
c.Send(bs, bs.Length, 0);//发送信息
/**////接受从服务器返回的信息
string recvStr = "";
byte[] recvBytes = new byte[1024];
int bytes;
//从服务器端接受返回信息
bytes = c.Receive(recvBytes, recvBytes.Length, 0);
recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
////显示服务器返回的验证信息
if(recvStr==”true”)
Console.WriteLine("验证成功:{0}", recvStr);
Else
Console.WriteLine("验证失败:{0}", recvStr); /**////一定记着用完socket后要关闭
c.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine("argumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException:{0}", e);
} Console.WriteLine("Press Enter to Exit");
}