- 论坛徽章:
- 0
|
10可用积分
客户端代码
void SocketSend(char *IpAddress, int Port, char *Type, char *parameter);
int _tmain(int argc, _TCHAR* argv[])
{
SocketSend("127.0.0.1", 50, "1", "数据收到否?\n");
return 0;
}
/******************************************************************************
* void SocketSend 发送Socket数据
* 参数
* IpAddress 接收服务器的IP地址
* Port 端口号双方必须保持一致
* Type 用于标识消息类型
* parameter 具体参数
******************************************************************************/
void SocketSend(char *IpAddress, int Port, char *Type, char *parameter)
{
char *msg[] = {NULL, NULL};
msg[0] = Type;
msg[1] = parameter;
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
//定义结构体
sockaddr_in sockAddr;
sockAddr.sin_family = AF_INET;
sockAddr.sin_addr.S_un.S_addr = inet_addr(IpAddress);
sockAddr.sin_port = htons(Port);
//建立连接
int a= connect(s, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR));
//发送数据
int b=send(s, *msg, sizeof(*msg), NULL);
//销毁
closesocket(s);
WSACleanup();
}
服务器端代码
void SocketRecv(int Port, char *Type, char *Parameter);
int _tmain(int argc, _TCHAR* argv[])
{
char *msg[] = {0, 0};
SocketRecv(50, &*msg[0], &*msg[1]);
printf_s(msg[0], msg[1]);
return 0;
}
/******************************************************************************
* void SocketRecv 接收Socket数据
* 参数
* Port 端口号双方必须保持一致
* Type 用于标识消息类型
* parameter 具体参数
******************************************************************************/
void SocketRecv(int Port, char *Type, char *Parameter)
{
char *msg[] = {0, 0};
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //创建TCP套接字
sockaddr_in sockaddr;
sockaddr.sin_family = AF_INET;
sockaddr.sin_addr.S_un.S_addr = INADDR_ANY;
sockaddr.sin_port = htons(Port);
bind(s, (SOCKADDR*)&sockaddr, sizeof(SOCKADDR));
listen(s, 30);
SOCKADDR ClientAddr;
int nSize = sizeof(SOCKADDR);
SOCKET ClientSock;
ClientSock = accept(s, (SOCKADDR*)&ClientAddr, &nSize);
char i = NULL;
recv(s, *msg, sizeof(*msg), NULL);
Type = msg[0];
Parameter = msg[1];
closesocket(ClientSock);
closesocket(s);
WSACleanup();
}
|
最佳答案
查看完整内容
char *msg = "";...................recv(ClientSock, Parameter, strlen(Parameter), NULL);strlen(Parameter) 就是0,你给了一个长度为0的缓冲区, 当然收不到数据。定义:char msg[80] = {'\0'};
|