通过网络接收和发送字符串

时间:2014-03-10 16:34:18

标签: c# networking

我必须通过网络向精确的计算机(具有已知IP)发送和接收字符串。为此,我写了以下内容:

void connect()
{
    epLocal = new IPEndPoint(IPAddress.Parse(localIp), localPort);
    sck.Bind(epLocal);

    epRemote = new IPEndPoint(IPAddress.Parse(remoteIp), remotePort);
    sck.Connect(epRemote);

    byte[] buffer = new byte[1500];
    sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);

    Console.WriteLine("Connected to " + remoteIp);
}

void sendMessage(string str)
{
    System.Text.ASCIIEncoding enc = new ASCIIEncoding();
    byte[] msg = new byte[8000];
    msg = enc.GetBytes(str);

    sck.Send(msg);
}

void MessageCallBack(IAsyncResult aResult)
{
    Console.WriteLine("Message received");

    int size = sck.EndReceiveFrom(aResult, ref epRemote);
    if (size > 0)
    {
        byte[] receivedData = new Byte[1464];
        receivedData = (byte[])aResult.AsyncState;

        ASCIIEncoding eEncpding = new ASCIIEncoding();
        string receivedMessage = eEncpding.GetString(receivedData);
        Console.WriteLine("received message:" + receivedMessage);
    }

    byte[] buffer = new byte[1500];
    sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
}

虽然,当我呼叫connect()然后sendMessage("Hello")时,我没有写任何内容显示收到的消息。为什么会这样?

0 个答案:

没有答案