I have just updated yApp.msi with a version containng four additional functions in the network node necessary to open a stream based TCP socket. I have tested it a little bit but also attached the source code so that you can see what’s going on. The idea is that the sockets never block. Hopefully that is so. Don’t use this version for anything else but to play around with the communication. A more stable editor is still to come.
Here is the lua script I used to test the code in the OnDeposit handler of the network node. The IP address is that of google com. I could connect and send, but I did not receive anything; probably because google didn’t send anything.
socket = event:connect("74.125.127.105", 80)
event:send(socket,"hello")
print(event:recv(socket,120)) // 120 is the number of bytes to read.
Here is the C++ code for the Lua functions. Let me know if you need any changes !
int ComNetwork::connect(lua_State *L)
{
SOCKET lSocket = INVALID_SOCKET;
if (lua_isstring(L, 1) && lua_isnumber(L,2))
{
const char* lAddress = lua_tostring(L,1);
int lPort = lua_tonumber(L,2);
sockaddr_in lServerAddress;
memset ((char *)&lServerAddress, 0, sizeof(struct sockaddr_in));
lServerAddress.sin_family=AF_INET;
lServerAddress.sin_port=htons(lPort);
lServerAddress.sin_addr.s_addr=inet_addr(lAddress);
lSocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (lSocket != INVALID_SOCKET)
{
ioctlsocket(lSocket, FIONBIO, (ULONG*)1);
if (::connect(lSocket,(SOCKADDR*)&lServerAddress,sizeof(sockaddr_in)) == SOCKET_ERROR)
{
::closesocket(lSocket);
}
}
else
{
LOG<0> () << "connect(): " << Message(WSAGetLastError());
}
}
lua_pushnumber(L, lSocket);
return 1;
}
int ComNetwork::recv(lua_State *L)
{
sBuffer[0] = '\0';
if (lua_isnumber(L,1) && lua_isnumber(L,2))
{
int lSocket = lua_tonumber(L,1);
int lRequest = lua_tonumber(L,2);
unsigned long lPending;
ioctlsocket(lSocket, FIONREAD, &lPending);
if (lPending >= lRequest)
{
int lReceived = ::recv(lSocket, sBuffer, lRequest, 0);
if (lReceived != SOCKET_ERROR)
{
sBuffer[lReceived+1] = '\0';
}
else
{
sBuffer[0] = '\0';
LOG<0> () << "recv(): " << Message(WSAGetLastError());
}
}
}
lua_pushstring(L, sBuffer);
return 1;
}
int ComNetwork::send(lua_State *L)
{
bool lResult = false;
if (lua_isnumber(L,1) && lua_isstring(L,2))
{
int lSocket = lua_tonumber(L,1);
const char* lString = lua_tostring(L,2);
if (::send(lSocket, lString, strlen(lString), 0) != SOCKET_ERROR)
{
lResult = true;
}
else
{
LOG<0> () << "send(): " << Message(WSAGetLastError());
}
}
lua_pushboolean(L, lResult);
return 0;
}
int ComNetwork::closesocket(lua_State *L)
{
if (lua_isnumber(L,1))
{
int lSocket = lua_isnumber(L,1);
::closesocket(lSocket);
}
return 0;
}