我一直在尝试为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();
}
}
}