Python Winsock - 如何通过已经激活的winsock连接发送数据

时间:2012-04-26 10:13:43

标签: python winsock ping irc

我的脚本是用大多数人不熟悉的不同语言编写的[MQL4]但是我已经将python功能导入到代码中,所以我可以在脚本中执行python代码。我的问题是,我正在使用MQL4连接到服务器,我想使用python通过其流发送数据。到目前为止,我只能让python创建自己的连接。反正有没有连接到已经打开的Windows套接字?

MQL代码

void ircconnect(){
int struct_sockaddr[4];
int addr, port_low, port_high;
int opts[1];
int c;

if (irc_disabled == 1) return(0);

// fill the sockaddr struct
addr = inet_addr(server_addr);
port_low = server_port & 0x00ff;
port_high = (server_port & 0xff00) >> 8; 
struct_sockaddr[0] = AF_INET | (port_high << 16) | (port_low << 24);
struct_sockaddr[1] = addr;
struct_sockaddr[2] = 0;
struct_sockaddr[3] = 0;

// connect
s = socket(AF_INET, SOCK_STREAM, 0);

opts[0] = 1000; // send timeout milliseconds
setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, opts, 4);

c = connect(s, struct_sockaddr, 16);

韵母代码

//Initialize Python Dll
PyInit();
PyExecute("from Tkinter import *");
PyExecute("root = Tk()");   

//Import necessary modules
PyExecute("import socket, os");

//Connect
PyExecute("network = \"irc.ircnetwork.com\"");
PyExecute("port = 6667");
PyExecute("irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)");
PyExecute("irc.connect((network, port))");

//Identify
PyExecute("irc.recv(1024)");
PyExecute("irc.send(\\"NICK Nick\\r\\n\")");
PyExecute("irc.send(\\"USER Nick Nick Nick :Nick IRC\\r\\n\")");
PyExecute("irc.send(\\"JOIN #channel\\r\\n\")");
PyExecute("irc.send(\"PRIVMSG NickServ IDENTIFY <pass>\\r\\n\")");
PyExecute("VERSION = \"version>\\r\\n\"");

//Listen for PING
PyExecute("while True:");
PyExecute("data = irc.recv(1024)");
PyExecute("print data");
PyExecute("if data.find(\"PING\") != -1:");

//Send PONG
PyExecute("irc.send(\"PONG \" + data.split() [ 1 ] + \"\\r\\n\")");
PyExecute("elif data.find(\"VERSION\") !=-1:");
PyExecute("irc.send(VERSION + \"\\r\\n\")");
PyExecute("elif data.find(\"NOTICE\") !=-1:");
PyExecute("nick = data.split(\"\!\") [ 0 ].replace (\":\", \"\" )");
PyExecute("message = \":\".join( data.split (\":\") [ 2: ] )");

1 个答案:

答案 0 :(得分:0)

这既可行又值得推荐。

比你的MQL代码可以“说话”任何交易对手 - 无论是PythonjavaC#/C++PHP,......,{{1} },...对手方。

不要冒险使用原始O / S套接字的麻烦和问题,而是使用像 ZeroMQ 这样的更高抽象方式,它具有由Austen Conrad移植和发布的 MQL4ZMQ 绑定,