簡體   English   中英

C# 套接字在同一台機器上發送和接收

[英]C# Socket Send and Receive on Same Machine

我正在制作一個可以在 Visual FoxPro 中訪問的 C# 套接字庫。 理想情況下,該庫將包含兩個函數:ReceiveMessage 和 SendMessage。 在每次調用時,該函數應該{打開連接 -> 讀/寫 -> 關閉連接}。 我在http://www.csharp-examples.net/socket-send-receive/找到了我要找的大部分內容; 但是,現在我必須在編譯 dll 之前測試(在同一台機器上)修改后的代碼。

我不斷收到“主動拒絕連接”錯誤。 雖然我已經包含了下面的所有代碼,以便您可以看到它在做什么,但問題幾乎肯定出在底部的 main() 中。 我對同一個端口不能有兩個連接的理解有限,但我不知道如何修復它。 有沒有人知道套接字,誰能給我一些關於如何測試這些功能的指導(我是套接字的新手)?

namespace Sockets
{
    class Sockets
    {
        private static void Receive(Socket socket, byte[] buffer, int offset, int size, int timeout)
        {
            int startTickCount = Environment.TickCount;
            int received = 0;  // how many bytes is already received
            do
            {
                if (Environment.TickCount > startTickCount + timeout)
                    throw new Exception("Timeout.");
                try
                {
                    received += socket.Receive(buffer, offset + received, size - received, SocketFlags.None);
                }
                catch (SocketException ex)
                {
                    if (ex.SocketErrorCode == SocketError.WouldBlock ||
                        ex.SocketErrorCode == SocketError.IOPending ||
                        ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
                    {
                        // socket buffer is probably empty, wait and try again
                        Thread.Sleep(30);
                    }
                    else
                        throw ex;  // any serious error occurr
                }
            } while (received < size);
        }
        // -----------------------------------------------------------------------------------------------------------------------
        // -----------------------------------------------------------------------------------------------------------------------
        // -----------------------------------------------------------------------------------------------------------------------
        private static void Send(Socket socket, byte[] buffer, int offset, int size, int timeout)
        {
            int startTickCount = Environment.TickCount;
            int sent = 0;  // how many bytes is already sent
            do
            {
                if (Environment.TickCount > startTickCount + timeout)
                    throw new Exception("Timeout.");
                try
                {
                    sent += socket.Send(buffer, offset + sent, size - sent, SocketFlags.None);
                }
                catch (SocketException ex)
                {
                    if (ex.SocketErrorCode == SocketError.WouldBlock ||
                        ex.SocketErrorCode == SocketError.IOPending ||
                        ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
                    {
                        // socket buffer is probably full, wait and try again
                        Thread.Sleep(30);
                    }
                    else
                        throw ex;  // any serious error occurr
                }
            } while (sent < size);
        }
        // -----------------------------------------------------------------------------------------------------------------------
        // -----------------------------------------------------------------------------------------------------------------------
        // -----------------------------------------------------------------------------------------------------------------------
        public static string SendMessage(string ipAddress, string port, string message)
        {               
            Socket socket = new TcpClient().Client;
            try
            {
            socket.Connect(ipAddress, Int32.Parse(port));

                Send(socket, Encoding.UTF8.GetBytes(message), 0, message.Length, 10000);
                socket.Close();
                return "Success";
            }
            catch (Exception e)
            {
                socket.Close();
                return e.Message;
            }
        }
        // -----------------------------------------------------------------------------------------------------------------------
        // -----------------------------------------------------------------------------------------------------------------------
        // -----------------------------------------------------------------------------------------------------------------------
        public static string ReceiveMessage(string ipAddress, string port, int bufferSize = 1024)
        {
            Socket socket = new TcpClient().Client;
            try
            {
            socket.Connect(ipAddress, Int32.Parse(port));
            byte[] buffer = new byte[bufferSize];

                Receive(socket, buffer, 0, buffer.Length, 10000);
                socket.Close();
                return Encoding.UTF8.GetString(buffer, 0, buffer.Length);
            }
            catch (Exception e)
            {
                socket.Close();
                return e.Message;
            }
        }
        // -----------------------------------------------------------------------------------------------------------------------
        // -----------------------------------------------------------------------------------------------------------------------
        // -----------------------------------------------------------------------------------------------------------------------

    }
}

class Program
{
    static void Main(string[] args)
    {
        new Thread(delegate() {var test = Sockets.Sockets.SendMessage("localhost", "60010", "abcdefg");}).Start();
        new Thread(delegate() {Console.WriteLine(Sockets.Sockets.ReceiveMessage("localhost", "60010"));}).Start();
        var waitForEnter = Console.ReadLine();
    }
} 

使用波浪號 (~) 作為尾隨字符,這里是功能接收函數(舊代碼已注釋):

public static string ReceiveMessage(string ipAddress, string port, int bufferSize = 1024)
{
    try
    {
        TcpListener serverSocket = new TcpListener(new System.Net.IPAddress(IPAddress.Parse(ipAddress).GetAddressBytes()), Int32.Parse(port));
        serverSocket.Start();
        TcpClient clientSocket = serverSocket.AcceptTcpClient();

        NetworkStream networkStream = clientSocket.GetStream();
        int bytesRead;
        string buffer = "";
        byte[] bytesFrom = new byte[bufferSize];

        while (true)
        {

            bytesRead = networkStream.Read(bytesFrom, 0, bytesFrom.Length);
            string incoming = System.Text.Encoding.ASCII.GetString(bytesFrom, 0, bytesRead);
            buffer = buffer + incoming;
            while (buffer.Contains("~"))
            {
                string msg = buffer.Substring(0, buffer.IndexOf("~"));
               // buffer = buffer.Remove(0, msg.Length + 3);
                return msg;
            }

        }


        //var socket = new TcpListener(new IPAddress(IPAddress.Parse(ipAddress).GetAddressBytes()), Int32.Parse(port));
        //try
        //{
        //byte[] buffer = new byte[bufferSize];

        //    Receive(socket, buffer, 0, buffer.Length, 10000);
        //    socket.Close();
        //    return Encoding.UTF8.GetString(buffer, 0, buffer.Length);
        //}
        //catch (Exception e)
        //{
        //    socket.Close();
        //    return e.Message;
        //}
    }
    catch (Exception e)
    {
        return e.Message;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM