zoukankan      html  css  js  c++  java
  • c# 异步通信网络中存在的问题

    服务器端接收从客户端传递来的数据:

    View Code
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
    namespace RecvFileServer
    {
        public class StateObject
        {
            // Client  socket.
            public Socket workSocket = null;
            // Size of receive buffer.
            public const int BufferSize = 1024;
            // Receive buffer.
            public byte[] buffer = new byte[BufferSize];
            // Received data string.
            public StringBuilder sb = new StringBuilder();
        }
    
        public class AsynchronousSocketServer
        {
    
            public static ManualResetEvent allDone = new ManualResetEvent(false);
            private static Socket serverSocket;
            public static void StartAsynchronousSocket()
            {
                Console.WriteLine("服务器启动成功");
                IPAddress ipAddress = IPAddress.Parse("192.168.0.40");
                IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 8083);
                serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                try
                {
                    serverSocket.Bind(ipEndPoint);
                    serverSocket.Listen(1000);
                    while (true)
                    {
                        allDone.Reset();
                        serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), serverSocket);
                        allDone.WaitOne();
                    }
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
    
    
            }
    
            public static void AcceptCallback(IAsyncResult ar)
            {
                //在此处输出连接到的ip地址。当连接成功的时候,进行接收数据。handle指代的是连接到的client的socket
                Socket listener = (Socket)ar.AsyncState;
                Socket handler = listener.EndAccept(ar);
                allDone.Set();
                StateObject states = new StateObject();
                states.workSocket = handler;
                handler.BeginReceive(states.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(RecvCallback), states);
            }
    
            public static void RecvCallback(IAsyncResult ar)
            {
                String content = String.Empty;
    
                //获取StateObject实例,并获取StateObject中的socket
                StateObject state = (StateObject)ar.AsyncState;
                Socket handler = state.workSocket;
    
                //从client socket接收数据
                int bytesRead = handler.EndReceive(ar);
    
                if (bytesRead > 0)
                {
                    // 可能有更多的数据,继续接收对应的数据.
                    state.sb.Append(Encoding.Unicode.GetString(
                        state.buffer, 0, bytesRead));
                    //判断读写的数据是否完成。如果没有,继续读写
    
                    content = state.sb.ToString();
                    int cc = content.IndexOf("<EOF>");
                    if (content.IndexOf("<EOF>") == -1)
                    {
                        //获取传输到的数据,并转为Unicode字符,以便支持中文
                        content = Encoding.Unicode.GetString(state.buffer, 0, bytesRead);
                        Console.WriteLine(content);
                        // Echo the data back to the client.
                        allDone.Set();
                    }
                }
                else
                {
                    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(RecvCallback), state);
                }
    
            }
        }
    }

    客户端发送数据方法:

    View Code
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
    namespace SendFileClient
    {
        class AsynchronousSocketClient
        {
            public static ManualResetEvent allDone = new ManualResetEvent(false);
            public static Socket client;
            public static void StartAsynchronousSocket()
            {
                IPAddress ipAddress = IPAddress.Parse("192.168.0.40");
                IPEndPoint ipPoint = new IPEndPoint(ipAddress, 8083);
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                client.BeginConnect(ipPoint, new AsyncCallback(ConnectCallBack), client);
                allDone.WaitOne();
                while (true)
                {
                    allDone.Reset();
                    Send(client, "现在客户端将向服务器端发送文件");
                    allDone.WaitOne();
                }
            }
    
            public static void ConnectCallBack(IAsyncResult args)
            {
                Socket client = (Socket)args.AsyncState;
                client.EndConnect(args);
                Console.WriteLine("Socket connected to {0}", client.RemoteEndPoint.ToString());
                allDone.Set();
            }
    
            public static void Send(Socket handler, String data)
            {
                // Convert the string data to byte data using ASCII encoding.
                byte[] byteData = Encoding.Unicode.GetBytes(data);
                // Begin sending the data to the remote device.此处发生错误?是否是因为其进行呢??
                handler.BeginSend(byteData, 0, byteData.Length, 0,
                    new AsyncCallback(SendCallback), handler);
            }
    
            private static void SendCallback(IAsyncResult ar)
            {
                try
                {
                    Socket handler = (Socket)ar.AsyncState;
                    int bytesSent = handler.EndSend(ar);
                    Console.WriteLine("Sent {0} bytes to server.", bytesSent);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }
    
        }
    }

    使用BeginRecv方法的时候,需要判断是否接收已经结束。使用String 。indexof("<EOF>")>-1方法

  • 相关阅读:
    (转)mtr命令详解诊断网络路由
    WinDbg使用介绍
    windbg-bp、 bm、 bu、 bl、 bc、 ba(断点、硬件断点)
    【转】25.windbg-!gle、g(错误码、g系列)
    umdh windbg分析内存泄露
    windbg !logexts(自带的监控API)
    windbg cs
    windbg dds、dps、dqs
    Windbg找出memory leak的一种笨办法
    【转】windows平台多线程同步之Mutex的应用
  • 原文地址:https://www.cnblogs.com/sdnyzhl/p/3056892.html
Copyright © 2011-2022 走看看