MSDN 的例子
服务端:
using System;
using System.Net.Sockets;
using System.Text;public class TcpTimeServer { private const int portNum = 13; public static int Main(String[] args) {
bool done = false;
TcpListener listener = new TcpListener(portNum); listener.Start(); while (!done) {
Console.Write("Waiting for connection...");
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("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 e) {
Console.WriteLine(e.ToString());
}
} listener.Stop(); return 0;
}
}
客户端:
using System;
using System.Net.Sockets;
using System.Text;public class TcpTimeClient {
private const int portNum = 13;
private const string hostName = "host.contoso.com"; public static int Main(String[] args) {
try {
TcpClient client = new TcpClient(hostName, portNum); NetworkStream ns = client.GetStream();
byte[] bytes = new byte[1024];
int bytesRead = ns.Read(bytes, 0, bytes.Length); Console.WriteLine(Encoding.ASCII.GetString(bytes,0,bytesRead)); client.Close(); } catch (Exception e) {
Console.WriteLine(e.ToString());
} return 0;
}
}
服务端:
using System;
using System.Net.Sockets;
using System.Text;public class TcpTimeServer { private const int portNum = 13; public static int Main(String[] args) {
bool done = false;
TcpListener listener = new TcpListener(portNum); listener.Start(); while (!done) {
Console.Write("Waiting for connection...");
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("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 e) {
Console.WriteLine(e.ToString());
}
} listener.Stop(); return 0;
}
}
客户端:
using System;
using System.Net.Sockets;
using System.Text;public class TcpTimeClient {
private const int portNum = 13;
private const string hostName = "host.contoso.com"; public static int Main(String[] args) {
try {
TcpClient client = new TcpClient(hostName, portNum); NetworkStream ns = client.GetStream();
byte[] bytes = new byte[1024];
int bytesRead = ns.Read(bytes, 0, bytes.Length); Console.WriteLine(Encoding.ASCII.GetString(bytes,0,bytesRead)); client.Close(); } catch (Exception e) {
Console.WriteLine(e.ToString());
} return 0;
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货