客户端
using System;
using System.Net;
using System.IO;
using System.Net.Sockets;
using System.Text;
namespace TCPClientDemo
{
class Program
{
const int ECHO_PORT = 8080;
static void Main(string[] args)
{
Console.Write("Your UserName:");
string userName = Console.ReadLine();
Console.WriteLine("-----Logged in-----");
try
{
//Create a connection with the Chatserver
TcpClient eClient = new TcpClient("127.0.0.1", ECHO_PORT);
//Create the stream classes
StreamReader readerStream = new StreamReader(eClient.GetStream());
NetworkStream writeStream = eClient.GetStream();
string dataToSend;
dataToSend = userName;
dataToSend += "\r\n";
//Send username to the server
byte[] data = Encoding.ASCII.GetBytes(dataToSend);
writeStream.Write(data, 0, data.Length);
while (true)
{
Console.WriteLine(userName + ":");
//Read line from server
dataToSend = Console.ReadLine();
dataToSend += "\r\n";
data = Encoding.ASCII.GetBytes(dataToSend);
writeStream.Write(data, 0, data.Length);
//If QUIT is sent, then quit application
if (dataToSend.IndexOf("QUIT") > -1)
break;
string returnData;
//Receive response from server
returnData = readerStream.ReadLine();
Console.WriteLine("Server: " + returnData);
}
服务器
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace TCPServerDemo
{
class ClientHandler
{
public TcpClient clientSocket;
public void RunClient()
{
//Create the stream classes
Console.WriteLine(clientSocket.Client.AddressFamily.ToString());
StreamReader readerStream = new StreamReader(clientSocket.GetStream());
NetworkStream writestream = clientSocket.GetStream();
byte[] dataWrite = Encoding.ASCII.GetBytes(returnData);
writestream.Write(dataWrite, 0, dataWrite.Length);
}
clientSocket.Close();
}
}
public class EchoServer
{
const int ECHO_PORT = 8080;
public static int nClient = 0;
static void Main(string[] args)
{
try
{
//Bind the Server to local port
TcpListener clientListener = new TcpListener(IPAddress.Parse("127.0.0.1"),ECHO_PORT);
//start to listen
clientListener.Start();
Console.WriteLine("Waiting for connection...");
while (true)
{
//Accept the connection
TcpClient client = clientListener.AcceptTcpClient();
ClientHandler cHandler = new ClientHandler();
//pass value to the ClientHandler object
cHandler.clientSocket = client;
string ipaddressport = client.Client.RemoteEndPoint.ToString();
Console.WriteLine(ipaddressport.Substring(0, ipaddressport.IndexOf(":")) + "--------------"+ipaddressport.Substring(ipaddressport.IndexOf(":")+1), ipaddressport.Length - ipaddressport.IndexOf(":")-1);
//Create a new thread for the client
Thread clientThread = new Thread(new ThreadStart(cHandler.RunClient));
clientThread.Start();
}
clientListener.Stop();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}