程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> C#網絡編程(同步傳輸字符串) - Part.2(6)

C#網絡編程(同步傳輸字符串) - Part.2(6)

編輯:關於C語言

接下來是客戶端:

class ClIEnt {
    static void Main(string[] args) {
        Console.WriteLine("ClIEnt Running ...");
        TcpClient clIEnt;
        ConsoleKey key;
        const int BufferSize = 8192;

        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();
        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);     // 獲得緩存
                try {
                    lock(streamToServer){
                        streamToServer.Write(buffer, 0, buffer.Length);     // 發往服務器
                    }
                    Console.WriteLine("Sent: {0}", msg);

                    int bytesRead;
                    buffer = new byte[BufferSize];
                    lock(streamToServer){
                        bytesRead = streamToServer.Read(buffer, 0, BufferSize);
                    }
                    msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);
                    Console.WriteLine("Received: {0}", msg);

                } catch (Exception ex) {
                    Console.WriteLine(ex.Message);
                    break;
                }
            }
        } while (key != ConsoleKey.X);

        streamToServer.Dispose();
        clIEnt.Close();

        Console.WriteLine("\n\n輸入\"Q\"鍵退出。");
        do {
            key = Console.ReadKey(true).Key;
        } while (key != ConsoleKey.Q);
    }
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved