TCP Client 及 Server 示例
时间:2011-06-04 来源:沧海小小粟
Client 端 Code:
public class TcpTimeClient
{
private const int portNum = 13;
private const string hostName = "LocalHost";
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));
Console.ReadKey();
client.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
return 0;
}
}
Server 端 Code:
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;
}
}