同步传输字符串

//服务端
        static void Main(string[] args)
        {
            
const int BufferSize = 8192;    // 缓存大小,8192字节

            Console.WriteLine(
"Server is running ... ");
            IPAddress ip 
= new IPAddress(new byte[] { 127001 });
            TcpListener listener 
= new TcpListener(ip, 8500);

            listener.Start();           
// 开始侦听
            Console.WriteLine("Start Listening ...");


            TcpClient remoteClient 
= listener.AcceptTcpClient();
            
// 打印连接到的客户端信息
            Console.WriteLine("Client Connected!{0} <-- {1}",
                remoteClient.Client.LocalEndPoint, remoteClient.Client.RemoteEndPoint);
            
// 获得流,并写入buffer中
            NetworkStream streamToClient = remoteClient.GetStream();

            
do
            {
                
byte[] buffer = new byte[BufferSize];
                
int bytesRead = streamToClient.Read(buffer, 0, BufferSize);
                Console.WriteLine(
"Reading data, {0} bytes ...", bytesRead);

                
// 获得请求的字符串 
                string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);
                Console.WriteLine(
"Received: {0}", msg);
            } 
while (true);
        }

 

 //客户端

    class Client
    {

        
static void Main(string[] args)
        {
            Console.WriteLine(
"Client Running ...");
            TcpClient client;

            
try
            {
                client 
= new TcpClient();
                client.Connect(
"localhost"8500);      // 与服务器连接
            }
            
catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                
return;
            }
            
// 打印连接到的服务端信息
            Console.WriteLine("Server Connected!{0} --> {1}",
                client.Client.LocalEndPoint, client.Client.RemoteEndPoint);

            NetworkStream streamToServer 
= client.GetStream();
            ConsoleKey key;
            Console.WriteLine(
"Menu: S - Send, X - Exit");
            
do
            {
                key 
= Console.ReadKey(true).Key;

                
if (key == ConsoleKey.S)
                {
                    
// 获取输入的字符串
                    Console.Write("Input the message: ");
                    
string msg = Console.ReadLine();

                    
byte[] buffer = Encoding.Unicode.GetBytes(msg);     // 获得缓存
                    streamToServer.Write(buffer, 0, buffer.Length);     // 发往服务器
                    Console.WriteLine("Sent: {0}", msg);
                }
            } 
while (key != ConsoleKey.X);
        }

 

posted @ 2010-06-04 17:00  小白.net  阅读(246)  评论(0编辑  收藏  举报