1

我一直在尝试为 Windows 8 编写 IRC 客户端应用程序。我遇到了一些问题。我从 pytho 的本教程开始:http: //oreilly.com/pub/h/1968 生成以下代码(对于 python 3.3)。它设法连接到服务器,被识别并登录,直到我关闭客户端。

server = "irc.location.net"
from socket import *

def main():
    s = socket(AF_INET, SOCK_STREAM)
    s.connect((server, 6667))
    readbuffer = ""
    s.send("NICK testIRC\r\n".encode())
    s.send("USER testIRC irc.location.net welcome :Test_IRC\r\n".encode())

    while 1:
        readbuffer = readbuffer + s.recv(1024).decode()
        temp = readbuffer.split("\n")
        readbuffer = temp.pop()

        for line in temp:
            line = line.rstrip();
            tokens = line.split(' ');

            if (tokens[0] == "PING"): 
                print("Got: %s\n" % line);
                response = "PONG %s\r\n" % tokens[1];
                s.send(response.encode())
                print("Sending: %s\n\n" % response)

if __name__ == "__main__":
    main();

然后我尝试将其移植到 C# (.NET 4.5),结果如下所示。但是,此代码给出的结果与 Python 代码不同。我认为可能会发生以下情况,但我不确定:服务器无法识别编码(我认为这很奇怪)。为了让一切变得更加奇怪,我得到了 1 个 ping,其中包含一些看起来像键(一些十六进制值)的东西,我当然会用 pong 来响应。在第一次 ping 之后,我什么也没有收到,我也没有在用户列表中列出。但是除了编码问题之外,我想不出任何东西。你们中有人能在我的代码中发现错误吗?提前非常感谢。

StreamSocket ss = new StreamSocket();
await ss.ConnectAsync(new HostName(server_address), 6667.ToString());

DataWriter dw = new DataWriter(ss.OutputStream);
DataReader dr = new DataReader(ss.InputStream);
dr.InputStreamOptions = InputStreamOptions.Partial;

// Text related stuff
byte[] bytes;

// register
bytes = enc.GetBytes("NICK testIRC\r\n"); // enc is of type Encoding and is created as an UTF8Encoding.
dw.WriteBytes(bytes);
bytes = enc.GetBytes("USER testIRC irc.location.net welcome :Test_IRC\r\n");
dw.WriteBytes(bytes);
await dw.StoreAsync();
await dw.FlushAsync();

int ping_count = 0;

while (true)
{
    await dr.LoadAsync(512);
    string msg = dr.ReadString(dr.UnconsumedBufferLength);

    string[] lines = msg.Split(new string[]{"\n"}, StringSplitOptions.RemoveEmptyEntries);
    foreach(string line in lines)
    {
        string cmd = line.TrimEnd('\r');

        if (cmd.StartsWith("PING "))
        {
            ping_count++;

            string[] tokens = cmd.Split(' ');

            // Create response
            string response = "PONG " + tokens[1];
            bytes = enc.GetBytes(response);

            dw.WriteBytes(bytes);
            dw.StoreAsync();
            dw.FlushAsync();
        }
    }
}
4

0 回答 0