首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

,c++写的关于socket的东西

2012-06-07 
求救,c++写的关于socket的东西我们老师给了我们一个关于socket的东西,用于客户端和服务器端连接的,作用是

求救,c++写的关于socket的东西
我们老师给了我们一个关于socket的东西,用于客户端和服务器端连接的,作用是先打开服务器端,再打开客户端,客户端输入一个内容然后server端回显出来,以下是代码

server.cpp
// Server.cpp : create a console application, and include the sources in the project
//
// 1. open the *.c in the Visual C++, then "rebuild all".
// 2. click "yes" to create a project workspace.
// 3. You need to -add the library 'ws2_32.lib' to your project 
// (Project -> Properties -> Linker -> Input -> Additional Dependencies) 
// 4. recompile the source.

#include "stdafx.h"
#include <winsock2.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define DEFAULT_PORT5019


int main(int argc, char **argv){

char szBuff[100];
int msg_len;
int addr_len;
struct sockaddr_in local, client_addr;

SOCKET sock, msg_sock;
WSADATA wsaData;

if (WSAStartup(0x202, &wsaData) == SOCKET_ERROR){
// stderr: standard error are printed to the screen.
fprintf(stderr, "WSAStartup failed with error %d\n", WSAGetLastError());
//WSACleanup function terminates use of the Windows Sockets DLL. 
WSACleanup();
return -1;
}
// Fill in the address structure
local.sin_family= AF_INET;
local.sin_addr.s_addr= INADDR_ANY;
local.sin_port= htons(DEFAULT_PORT);

sock = socket(AF_INET,SOCK_STREAM, 0);//TCp socket


if (sock == INVALID_SOCKET){
fprintf(stderr, "socket() failed with error %d\n", WSAGetLastError());
WSACleanup();
return -1;
}

if (bind(sock, (struct sockaddr *)&local, sizeof(local)) == SOCKET_ERROR){
fprintf(stderr, "bind() failed with error %d\n", WSAGetLastError());
WSACleanup();
return -1;
}

//waiting for the connections
if (listen(sock, 5) == SOCKET_ERROR){
fprintf(stderr, "listen() failed with error %d\n", WSAGetLastError());
WSACleanup();
return -1;
}


printf("Waiting for the connections ........\n");

addr_len = sizeof(client_addr);
msg_sock = accept(sock, (struct sockaddr*)&client_addr, &addr_len);
if (msg_sock == INVALID_SOCKET){
fprintf(stderr, "accept() failed with error %d\n", WSAGetLastError());
WSACleanup();
return -1;
}

printf("accepted connection from %s, port %d\n",
inet_ntoa(client_addr.sin_addr),
htons(client_addr.sin_port));

msg_len = recv(msg_sock, szBuff, sizeof(szBuff), 0);

if (msg_len == SOCKET_ERROR){
fprintf(stderr, "recv() failed with error %d\n", WSAGetLastError());
WSACleanup();
return -1;
}

if (msg_len == 0){
printf("Client closed connection\n");
closesocket(msg_sock);
return -1;
}

printf("Bytes Received: %d, message: %s from %s\n", msg_len, szBuff, inet_ntoa(client_addr.sin_addr));

msg_len = send(msg_sock, szBuff, sizeof(szBuff), 0);
if (msg_len == 0){
printf("Client closed connection\n");
closesocket(msg_sock);
return -1;
}

closesocket(msg_sock);
WSACleanup();
}




client.cpp
// Client.cpp : Defines the entry point for the console application.
//
// 1. open the *.c in the Visual C++, then "rebuild all".
// 2. click "yes" to create a project workspace.
// 3. You need to -add the library 'ws2_32.lib' to your project 
// (Project -> Properties -> Linker -> Input -> Additional Dependencies) 
// 4. recompile the source.


#include "stdafx.h"
#include <winsock2.h>
#include <stdlib.h>
#include <stdio.h>


#include <string.h>


#define DEFAULT_PORT5019


int main(int argc, char **argv){
argc=3;
char szBuff[100];
int msg_len;
//int addr_len;
struct sockaddr_in server_addr;
struct hostent *hp;
SOCKET connect_sock;
WSADATA wsaData;

char*server_name = "localhost";
unsigned shortport = DEFAULT_PORT;
unsigned intaddr;

if (argc != 3){
printf("echoscln [server name] [port number]\n");
return -1;
}
else{

}

if (WSAStartup(0x202, &wsaData) == SOCKET_ERROR){
// stderr: standard error are printed to the screen.
fprintf(stderr, "WSAStartup failed with error %d\n", WSAGetLastError());
//WSACleanup function terminates use of the Windows Sockets DLL. 
WSACleanup();
return -1;
}

if (isalpha(server_name[0]))
hp = gethostbyname(server_name);
else{
addr = inet_addr(server_name);
hp = gethostbyaddr((char*)&addr, 4, AF_INET);
}

if (hp==NULL)
{
fprintf(stderr, "Cannot resolve address: %d\n", WSAGetLastError());
WSACleanup();
return -1;
}

//copy the resolved information into the sockaddr_in structure
memset(&server_addr, 0, sizeof(server_addr));
memcpy(&(server_addr.sin_addr), hp->h_addr, hp->h_length);
server_addr.sin_family = hp->h_addrtype;
server_addr.sin_port = htons(port);


connect_sock = socket(AF_INET,SOCK_STREAM, 0);//TCp socket


if (connect_sock == INVALID_SOCKET){
fprintf(stderr, "socket() failed with error %d\n", WSAGetLastError());
WSACleanup();
return -1;
}

printf("Client connecting to: %s\n", hp->h_name);

if (connect(connect_sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) 
== SOCKET_ERROR){
fprintf(stderr, "connect() failed with error %d\n", WSAGetLastError());
WSACleanup();
return -1;
}


printf("input character string:\n");
gets(szBuff);

msg_len = send(connect_sock, szBuff, sizeof(szBuff), 0);

if (msg_len == SOCKET_ERROR){
fprintf(stderr, "send() failed with error %d\n", WSAGetLastError());
WSACleanup();
return -1;
}

if (msg_len == 0){
printf("server closed connection\n");
closesocket(connect_sock);
WSACleanup();
return -1;
}

msg_len = recv(connect_sock, szBuff, sizeof(szBuff), 0);

if (msg_len == SOCKET_ERROR){
fprintf(stderr, "send() failed with error %d\n", WSAGetLastError());
closesocket(connect_sock);
WSACleanup();
return -1;
}

if (msg_len == 0){
printf("server closed connection\n");
closesocket(connect_sock);
WSACleanup();
return -1;
}

printf("Echo from the server %s.\n", szBuff);

closesocket(connect_sock);
WSACleanup();
}


但是运行的时候输入之后两个窗口就自动关掉了,有没有那位高手能说说现在是个什么情况啊,谢谢了??





[解决办法]

C/C++ code
server.cpp // Server.cpp : create a console application, and include the sources in the project // // 1. open the *.c in the Visual C++, then "rebuild all". // 2. click "yes" to create a project workspace. // 3. You need to -add the library 'ws2_32.lib' to your project //    (Project -> Properties -> Linker -> Input -> Additional Dependencies) // 4. recompile the source. #include "stdafx.h" #include <winsock2.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #define DEFAULT_PORT 5019 int main(int argc, char **argv){ char szBuff[100]; int msg_len; int addr_len; struct sockaddr_in local, client_addr; SOCKET sock, msg_sock; WSADATA wsaData; if (WSAStartup(0x202, &wsaData) == SOCKET_ERROR){ // stderr: standard error are printed to the screen. fprintf(stderr, "WSAStartup failed with error %d\n", WSAGetLastError()); //WSACleanup function terminates use of the Windows Sockets DLL. WSACleanup(); return -1; } // Fill in the address structure local.sin_family = AF_INET; local.sin_addr.s_addr = INADDR_ANY; local.sin_port = htons(DEFAULT_PORT); sock = socket(AF_INET,SOCK_STREAM, 0); //TCp socket if (sock == INVALID_SOCKET){ fprintf(stderr, "socket() failed with error %d\n", WSAGetLastError()); WSACleanup(); return -1; } if (bind(sock, (struct sockaddr *)&local, sizeof(local)) == SOCKET_ERROR){ fprintf(stderr, "bind() failed with error %d\n", WSAGetLastError()); WSACleanup(); return -1; } //waiting for the connections if (listen(sock, 5) == SOCKET_ERROR){ fprintf(stderr, "listen() failed with error %d\n", WSAGetLastError()); WSACleanup(); return -1; } printf("Waiting for the connections ........\n"); addr_len = sizeof(client_addr); msg_sock = accept(sock, (struct sockaddr*)&client_addr, &addr_len); if (msg_sock == INVALID_SOCKET){ fprintf(stderr, "accept() failed with error %d\n", WSAGetLastError()); WSACleanup(); return -1; } printf("accepted connection from %s, port %d\n", inet_ntoa(client_addr.sin_addr), htons(client_addr.sin_port)); msg_len = recv(msg_sock, szBuff, sizeof(szBuff), 0); if (msg_len == SOCKET_ERROR){ fprintf(stderr, "recv() failed with error %d\n", WSAGetLastError()); WSACleanup(); return -1; } if (msg_len == 0){ printf("Client closed connection\n"); closesocket(msg_sock); return -1; } printf("Bytes Received: %d, message: %s from %s\n", msg_len, szBuff, inet_ntoa(client_addr.sin_addr)); msg_len = send(msg_sock, szBuff, sizeof(szBuff), 0); if (msg_len == 0){ printf("Client closed connection\n"); closesocket(msg_sock); return -1; } closesocket(msg_sock); WSACleanup(); } client.cpp // Client.cpp : Defines the entry point for the console application. // // 1. open the *.c in the Visual C++, then "rebuild all". // 2. click "yes" to create a project workspace. // 3. You need to -add the library 'ws2_32.lib' to your project //    (Project -> Properties -> Linker -> Input -> Additional Dependencies) // 4. recompile the source. #include "stdafx.h" #include <winsock2.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #define DEFAULT_PORT 5019 int main(int argc, char **argv){ argc=3; char szBuff[100]; int msg_len; //int addr_len; struct sockaddr_in server_addr; struct hostent *hp; SOCKET connect_sock; WSADATA wsaData; char *server_name = "localhost"; unsigned short port = DEFAULT_PORT; unsigned int addr; if (argc != 3){ printf("echoscln [server name] [port number]\n"); return -1; } else{ } if (WSAStartup(0x202, &wsaData) == SOCKET_ERROR){ // stderr: standard error are printed to the screen. fprintf(stderr, "WSAStartup failed with error %d\n", WSAGetLastError()); //WSACleanup function terminates use of the Windows Sockets DLL. WSACleanup(); return -1; } if (isalpha(server_name[0])) hp = gethostbyname(server_name); else{ addr = inet_addr(server_name); hp = gethostbyaddr((char*)&addr, 4, AF_INET); } if (hp==NULL) { fprintf(stderr, "Cannot resolve address: %d\n", WSAGetLastError()); WSACleanup(); return -1; } //copy the resolved information into the sockaddr_in structure memset(&server_addr, 0, sizeof(server_addr)); memcpy(&(server_addr.sin_addr), hp->h_addr, hp->h_length); server_addr.sin_family = hp->h_addrtype; server_addr.sin_port = htons(port); connect_sock = socket(AF_INET,SOCK_STREAM, 0); //TCp socket if (connect_sock == INVALID_SOCKET){ fprintf(stderr, "socket() failed with error %d\n", WSAGetLastError()); WSACleanup(); return -1; } printf("Client connecting to: %s\n", hp->h_name); if (connect(connect_sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) == SOCKET_ERROR){ fprintf(stderr, "connect() failed with error %d\n", WSAGetLastError()); WSACleanup(); return -1; } printf("input character string:\n"); gets(szBuff); msg_len = send(connect_sock, szBuff, sizeof(szBuff), 0); if (msg_len == SOCKET_ERROR){ fprintf(stderr, "send() failed with error %d\n", WSAGetLastError()); WSACleanup(); return -1; } if (msg_len == 0){ printf("server closed connection\n"); closesocket(connect_sock); WSACleanup(); return -1; } msg_len = recv(connect_sock, szBuff, sizeof(szBuff), 0); if (msg_len == SOCKET_ERROR){ fprintf(stderr, "send() failed with error %d\n", WSAGetLastError()); closesocket(connect_sock); WSACleanup(); return -1; } if (msg_len == 0){ printf("server closed connection\n"); closesocket(connect_sock); WSACleanup(); return -1; } printf("Echo from the server %s.\n", szBuff); closesocket(connect_sock); WSACleanup(); } 


[解决办法]
服务器端没有设置 循环接收, 
可以在 
msg_len = recv(msg_sock, szBuff, sizeof(szBuff), 0); 
之前加个while循环

客户端也是发送完了,就直接结束了, 也可以加个while循环
[解决办法]
使用事件等待
[解决办法]

C/C++ code
#include "stdafx.h" #include <winsock2.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #define DEFAULT_PORT 5019 int main(int argc, char **argv){ char szBuff[100]; int msg_len; int addr_len; struct sockaddr_in local, client_addr; SOCKET sock, msg_sock; WSADATA wsaData; if (WSAStartup(0x202, &wsaData) == SOCKET_ERROR){ // stderr: standard error are printed to the screen. fprintf(stderr, "WSAStartup failed with error %d\n", WSAGetLastError()); //WSACleanup function terminates use of the Windows Sockets DLL. WSACleanup(); return -1; } // Fill in the address structure local.sin_family = AF_INET; local.sin_addr.s_addr = INADDR_ANY; local.sin_port = htons(DEFAULT_PORT); sock = socket(AF_INET,SOCK_STREAM, 0); //TCp socket if (sock == INVALID_SOCKET){ fprintf(stderr, "socket() failed with error %d\n", WSAGetLastError()); WSACleanup(); return -1; } if (bind(sock, (struct sockaddr *)&local, sizeof(local)) == SOCKET_ERROR){ fprintf(stderr, "bind() failed with error %d\n", WSAGetLastError()); WSACleanup(); return -1; } //waiting for the connections if (listen(sock, 5) == SOCKET_ERROR){ fprintf(stderr, "listen() failed with error %d\n", WSAGetLastError()); WSACleanup(); return -1; } printf("Waiting for the connections ........\n"); addr_len = sizeof(client_addr);while(1){ msg_sock = accept(sock, (struct sockaddr*)&client_addr, &addr_len); if (msg_sock == INVALID_SOCKET){ fprintf(stderr, "accept() failed with error %d\n", WSAGetLastError()); WSACleanup(); return -1; } printf("accepted connection from %s, port %d\n", inet_ntoa(client_addr.sin_addr), htons(client_addr.sin_port)); msg_len = recv(msg_sock, szBuff, sizeof(szBuff), 0); if (msg_len == SOCKET_ERROR){ fprintf(stderr, "recv() failed with error %d\n", WSAGetLastError()); WSACleanup(); return -1; } if (msg_len == 0){ printf("Client closed connection\n"); closesocket(msg_sock); return -1; } printf("Bytes Received: %d, message: %s from %s\n", msg_len, szBuff, inet_ntoa(client_addr.sin_addr)); msg_len = send(msg_sock, szBuff, sizeof(szBuff), 0); if (msg_len == 0){ printf("Client closed connection\n"); closesocket(msg_sock); return -1; } }closesocket(msg_sock); WSACleanup(); }
[解决办法]
服务器端程序时不应该随便退出的,你的这个程序在服务器端accept一次之后,处理完就玩完了。让你的服务器在accept到处理数据放在一个死循环里。客户端随时通讯,服务端随时处理。通知机制就不用了,accept是阻塞的,放在那儿只有当客户连接时才会往下走。
[解决办法]
控制台的代码往往要在末尾加上 getch() 或 system("pause"),
暂停一下
[解决办法]
你的server.cpp中:
在printf("Waiting for the connections ........\n"); 后,如果不想让服务器退出的话,应该这样做:



while (true)
{
msg_sock = accept(sock, (struct sockaddr*)&client_addr, &addr_len); 
if (msg_sock == INVALID_SOCKET)

fprintf(stderr, "accept() failed with error %d\n", WSAGetLastError()); 
return -1; 
}

//连接成功
//此时用recv接收客户端数据,如果客户端不发送数据,也不关闭,则服务器永远在这里等待
msg_len = recv(msg_sock, szBuff, sizeof(szBuff), 0); 
//判断recv是否出错,如果出错,则做异常处理 (我这里就不写了)

//接收完数据后,服务器发送数据。


send(....)
//判断send是否出错,如果出错,则做异常处理 (我这里就不写了)

//关闭客户端连接.再等待客户端连接
closesocket(msg_sock)
}



你这个服务器一个时刻只能处理一个客户端。新手先把这些搞懂后,再去学习处理多个客户端吧。
你这个socket是阻塞式的,后面你可以把它设为非阻塞式的(ioctl 函数),配合select来了解socket

热点排行
Bad Request.