| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 479 人关注过本帖
标题:socket编程,连接问题??
取消只看楼主 加入收藏
sycamore
Rank: 1
等 级:新手上路
帖 子:2
专家分:0
注 册:2005-12-16
收藏
 问题点数:0 回复次数:0 
socket编程,连接问题??

在本机测试可以连接,二台电脑测试就不行了,这是为什么??


服务器代码:

#include <iostream>
#include <stdlib.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
using namespace std;

int main()
{
WORD wVersionRequested;
WSADATA wsaData;
SOCKET sock_id, client_id;
struct sockaddr_in serv_addr, remote_addr;

wVersionRequested = MAKEWORD(2, 0);

if (0 != WSAStartup(wVersionRequested, &wsaData))
{
cout << "加载Winsock库出错!" << endl;
exit(1);
}

if (-1 == (sock_id = socket(AF_INET, SOCK_STREAM, 0)))
{
cout << "创建套接字出错!" << endl;
exit(1);
}

serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(800);
serv_addr.sin_addr.S_un.S_addr = inet_addr("192.168.1.10");
memset(&(serv_addr.sin_zero), 0, sizeof(serv_addr.sin_zero));

if (SOCKET_ERROR == bind(sock_id, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr)))
{
cout << "1出错!" << endl;
exit(1);
}

if (SOCKET_ERROR == listen(sock_id, 5))
{
cout << "2出错!" << endl;
exit(1);
}

int sin_size = sizeof(struct sockaddr_in);
if (SOCKET_ERROR == (client_id = accept(sock_id, (struct sockaddr *)&remote_addr, &sin_size)))
{
cout << "3出错!" << endl;
exit(1);
}

send(client_id, "Hello World!", strlen("Hello World!"), 0);

closesocket(client_id);

closesocket(sock_id);
WSACleanup();
return 0;
}


客户端代码:

#include <iostream>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
using namespace std;

int main()
{
const int SIZE = 100;
char temp[SIZE];
int recvbytes;
WORD wVersionRequested;
WSADATA wsaData;
SOCKET sock_id, client_id;
struct sockaddr_in serv_addr;

wVersionRequested = MAKEWORD(2, 0);
if (0 != WSAStartup(wVersionRequested, &wsaData))
{
cout << "加载Winsock库出错!" << endl;
exit(1);
}

if (-1 == (sock_id = socket(AF_INET, SOCK_STREAM, 0)))
{
cout << "出错!" << endl;
exit(1);
}

serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(800);
serv_addr.sin_addr.S_un.S_addr = inet_addr("192.168.1.10");
memset(&(serv_addr.sin_zero), 0, sizeof(serv_addr.sin_zero));

if (SOCKET_ERROR == (client_id = connect(sock_id, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr))))
{
cout << "出错!" << endl;
exit(1);
}


if (ERROR_SUCCESS == (recvbytes = recv(sock_id, temp, SIZE, 0)))
{
cout << "接受数据出错!" << endl;
exit(1);
}
temp[recvbytes] = '\0';
cout << temp << endl;

closesocket(client_id);
closesocket(sock_id);


WSACleanup();
return 0;
}

搜索更多相关主题的帖子: socket 
2007-07-22 15:06
快速回复:socket编程,连接问题??
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.038364 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved