WEB开发网
开发学院软件开发C语言 C#网络编程(异步传输字符串) - Part.3 阅读

C#网络编程(异步传输字符串) - Part.3

 2009-03-26 08:20:01 来源:WEB开发网   
核心提示: 随后,我们在主程序中仅仅创建TcpListener类型实例,C#网络编程(异步传输字符串) - Part.3(7),由于RemoteClient类在构造函数中已经完成了初始化的工作,所以我们在下面的while循环中我们甚至不需要调用任何方法:class Server { static vo

随后,我们在主程序中仅仅创建TcpListener类型实例,由于RemoteClient类在构造函数中已经完成了初始化的工作,所以我们在下面的while循环中我们甚至不需要调用任何方法:

class Server {
    static void
Main(string[] args) {
        Console.WriteLine("Server is running ... ");
        IPAddress ip = new IPAddress(new byte[] { 127, 0, 0, 1 });
        TcpListener listener = new TcpListener(ip, 8500);

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

        while (true) {
            // 获取一个连接,同步方法,在此处中断
            TcpClient client = listener.AcceptTcpClient();             
            RemoteClient wapper = new RemoteClient(client);
        }
    }
}

好了,服务端的实现现在就完成了,接下来我们再看一下客户端的实现:

2.客户端的实现

与服务端类似,我们首先对TcpClient进行一个简单的包装,使它的使用更加方便一些,因为它是服务端的客户,所以我们将类的名称命名为ServerClient:

public class ServerClient {
    private const int BufferSize = 8192;
    private byte[] buffer;
    private TcpClient client;
    private NetworkStream streamToServer;
    private string msg = "Welcome to TraceFact.Net!";

    public ServerClient() {
        try {
            client = new TcpClient();
            client.Connect("localhost", 8500);      // 与服务器连接
        } catch (Exception ex) {
            Console.WriteLine(ex.Message);
            return;
        }
        buffer = new byte[BufferSize];

        // 打印连接到的服务端信息
        Console.WriteLine("Server Connected!{0} --> {1}",
            client.Client.LocalEndPoint, client.Client.RemoteEndPoint);

        streamToServer = client.GetStream();
    }

    // 连续发送三条消息到服务端
    public void SendMessage(string msg) {

        msg = String.Format("[length={0}]{1}", msg.Length, msg);

        for (int i = 0; i <= 2; i++) {
            byte[] temp = Encoding.Unicode.GetBytes(msg);   // 获得缓存
            try {
                streamToServer.Write(temp, 0, temp.Length); // 发往服务器
                Console.WriteLine("Sent: {0}", msg);
            } catch (Exception ex) {
                Console.WriteLine(ex.Message);
                break;
            }
        }

        lock (streamToServer) {
            AsyncCallback callBack = new AsyncCallback(ReadComplete);
            streamToServer.BeginRead(buffer, 0, BufferSize, callBack, null);
        }
    }

    public void SendMessage() {
        SendMessage(this.msg);
    }

    // 读取完成时的回调方法
    private void ReadComplete(IAsyncResult ar) {
        int bytesRead;

        try {
            lock (streamToServer) {
                bytesRead = streamToServer.EndRead(ar);
            }
            if (bytesRead == 0) throw new Exception("读取到0字节");

            string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);
            Console.WriteLine("Received: {0}", msg);
            Array.Clear(buffer, 0, buffer.Length);      // 清空缓存,避免脏读

            lock (streamToServer) {
                AsyncCallback callBack = new AsyncCallback(ReadComplete);
                streamToServer.BeginRead(buffer, 0, BufferSize, callBack, null);
            }
        } catch (Exception ex) {
            if(streamToServer!=null)
                streamToServer.Dispose();
            client.Close();

            Console.WriteLine(ex.Message);
        }
    }
}

上一页  2 3 4 5 6 7 8  下一页

Tags:网络编程 异步 传输

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接