C#通过localhost上的TcpSockets发送/接收数据

时间:2015-08-04 18:05:40

标签: c# sockets tcpsocket

我正在尝试通过本地计算机上的TcpSockets发送和接收数据。

我尝试使用本教程:http://www.csharp-examples.net/socket-send-receive/

因此我有两个功能"接收"和"发送":

我的代码:

public static void Main()
{
    Socket socket = new TcpClient("Ultimate-PC", 8080).Client;
    byte[] buffer = new byte[12];
    string txt = "Hello";
    try
    {
        Send(socket,Encoding.UTF8.GetBytes(txt), 0, Encoding.UTF8.GetBytes(txt).Length,10000);
        Receive(socket, buffer, 0, buffer.Length, 10000);
        string str = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
        Console.WriteLine(str);
    }
    catch (Exception)
    {

        throw;
    }
}

public 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)
            {
                Thread.Sleep(30);
            }
            else
                throw ex;
        }
    } while (sent < size);
}

public static void Receive(Socket socket, byte[] buffer, int offset, int size, int timeout)
{
    int startTickCount = Environment.TickCount;
    int received = 0;
    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)
            {
                Thread.Sleep(30);
            }
            else
                throw ex;
        }
    } while (received < size);
}

问题是,在套接字初始化后,在调试模式下没有任何反应。任何想法我怎么能让它工作?

0 个答案:

没有答案