Chinaunix
标题:
PHP与C++通信遇到一个问题!
[打印本页]
作者:
lbblscy
时间:
2007-01-29 09:51
标题:
PHP与C++通信遇到一个问题!
php端的代码如下:
<?php
$sh = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (socket_connect($sh, '127.0.0.1', 27015)) {
echo "Socket connected correctly<br>";
}
$buf = 'Test Message';
$len = strlen($buf);
if (socket_send($sh, $buf, $len, 0x1) !== false) {
echo "Message sent correctly";
}
socket_close($sh);
?>
复制代码
C++的服务端:
#include <windows.h>
#include <iostream.h>
#include <Winsock2.h>
#define NO_FLAGS_SET 0
#define PORT (u_short) 27015
#define MAXBUFLEN 1024
INT main(VOID)
{
WSADATA Data;
SOCKADDR_IN serverSockAddr;
SOCKADDR_IN clientSockAddr;
SOCKET serverSocket;
SOCKET clientSocket;
int addrLen=sizeof(SOCKADDR_IN);
int status;
int numrcv;
char buffer[MAXBUFLEN] = "\0";
/* initialize the Windows Socket DLL */
status=WSAStartup(MAKEWORD(2, 1), &Data);
if (status != 0)
cerr << "ERROR: WSAStartup unsuccessful" << endl;
/* zero the sockaddr_in structure */
memset(&serverSockAddr, 0, sizeof(serverSockAddr));
/* specify the port portion of the address */
serverSockAddr.sin_port=htons(PORT);
/* specify the address family as Internet */
serverSockAddr.sin_family=AF_INET;
/* specify that the address does not matter */
serverSockAddr.sin_addr.s_addr=htonl(INADDR_ANY);
/* create a socket */
serverSocket=socket(AF_INET, SOCK_STREAM, 0);
if (serverSocket == INVALID_SOCKET)
cerr << "ERROR: socket unsuccessful" << endl;
/* associate the socket with the address */
status=bind(serverSocket, (LPSOCKADDR) &serverSockAddr, sizeof(serverSockAddr));
if (status == SOCKET_ERROR)
cerr << "ERROR: bind unsuccessful" << endl;
/* allow the socket to take connections */
status=listen(serverSocket, 1);
if (status == SOCKET_ERROR)
cerr << "ERROR: listen unsuccessful" << endl;
/* accept the connection request when one
is received */
clientSocket=accept(serverSocket, (LPSOCKADDR) &clientSockAddr, &addrLen);
cout << "Got the connection..." << endl;
while(1)
{
numrcv=recv(clientSocket, buffer, MAXBUFLEN, NO_FLAGS_SET);
if ((numrcv == 0) || (numrcv == SOCKET_ERROR))
{
cout << "Connection terminated." << endl;
status=closesocket(clientSocket);
if (status == SOCKET_ERROR)
cerr << "ERROR: closesocket unsuccessful" << endl;
status=WSACleanup();
if (status == SOCKET_ERROR)
cerr << "ERROR: WSACleanup unsuccessful" << endl;
return(1);
}
cout << buffer << endl;
} /* while */
}
复制代码
现在遇到的问题是:PHP送出的字符串“Test Message”,服务器端显示的为“Test Messagq”,最后一位出错了。我的编译环境为MinGW。请大虾们指点。
作者:
newzy
时间:
2007-01-29 11:44
可以参考下这个示例, "CGI 与后台程序用 socket 进行消息通信"
http://www.eybuild.com/develop/download.htm#sendmsg
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2