您的位置:首页 > 其它

多线程服务器(一个服务器处理多个客户端,端口复

2017-03-16 18:10 330 查看
服务器端

#undef UNICODE

#define WIN32_LEAN_AND_MEAN

#include "stdafx.h"

#include <winsock2.h>

#include <ws2tcpip.h>

#include <windows.h>

#include <iphlpapi.h>

#include <stdio.h>

#define DEFAULT_PORT "27015"

#define DEFAULT_BUFLEN 1024

#pragma comment(lib, "Ws2_32.lib")

SOCKET GLOBAL[100];

DWORD WINAPI handle_a_connect(LPVOID aa)

{
SOCKET ClientSocket = *(SOCKET*)aa;

struct sockaddr addr;
struct sockaddr_in* addr_v4;
int addr_len = sizeof(addr);

//获取local ip and port
ZeroMemory(&addr, sizeof(addr));
if (0 == getsockname(ClientSocket, &addr, &addr_len)){
   if (addr.sa_family == AF_INET){
       addr_v4 = (sockaddr_in*)&addr;

       char *nSourceIP = inet_ntoa(addr_v4.sin_addr)

          int nSourcePort = addr_v4.sin_port;

    }
}
//获取remote ip and port
ZeroMemory(&addr, sizeof(addr));
if (0 == getpeername(s, &addr, &addr_len)){

    if (addr.sa_family == AF_INET){

        addr_v4 = (sockaddr_in*)&addr;

       char *nDestIP = inet_ntoa(addr_v4.sin_addr)

          int nDestPort = addr_v4.sin_port;

    }
}

char recvbuf[DEFAULT_BUFLEN];
int iResult;
do {
iResult = recv(ClientSocket, recvbuf, DEFAULT_BUFLEN, 0);
if (iResult > 0) {
printf("Server received: %s from %s:%d(i am %s:%d)\n", recvbuf,nSourceIP, nSourcePort, nDestIP, nDestPort);

// Echo the buffer back to the sender
int iSendResult = send(ClientSocket, recvbuf, iResult, 0);
if (iSendResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
while (1);
return 1;
}
printf("Server send: %s from %s:%d(i am %s:%d)\n", recvbuf,nSourceIP, nSourcePort, nDestIP, nDestPort);
}
else if (iResult == 0){
printf("Connection closing...\n");
iResult = shutdown(ClientSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
while (1);
return 1;
}
closesocket(ClientSocket);
}
else {
printf("recv failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
while (1);
return 1;
}
} while (iResult > 0);
return 0;

}

int main(void)

{
WSADATA wsaData;
int iResult;
SOCKET ListenSocket = INVALID_SOCKET;
SOCKET ClientSocket = INVALID_SOCKET;
struct addrinfo *result = NULL;
struct addrinfo hints;
int iSendResult;
char recvbuf[DEFAULT_BUFLEN];
//int recvbuflen = DEFAULT_BUFLEN;

// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
while (1);
return 1;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;

// Resolve the server address and port
iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
while (1);
return 1;
}

// Create a SOCKET for connecting to server
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
while (1);
return 1;
}

// Setup the TCP listening socket
iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR) {
printf("bind failed with error: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(ListenSocket);
WSACleanup();
while (1);
return 1;
}
freeaddrinfo(result);
iResult = listen(ListenSocket, SOMAXCONN);
if (iResult == SOCKET_ERROR) {
printf("listen failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
while (1);
return 1;
}

// Accept a client socket
int i=0;
while(1){
ClientSocket = accept(ListenSocket, NULL, NULL);
i = (i+1) % 100;
if (ClientSocket == INVALID_SOCKET) {
printf("accept failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
while (1);
return 1;
}
GLOBAL[i] = ClientSocket;
HANDLE hand = CreateThread(NULL, 0, handle_a_connect, &GLOBAL[i], 0, NULL);
}

// No longer need server socket
closesocket(ListenSocket);
WSACleanup();
while (1);
return 0;

}

客户端

#include "stdafx.h"
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <iphlpapi.h>
#include <stdio.h>
#define DEFAULT_PORT "27015"
#define DEFAULT_BUFLEN 1024
#pragma comment(lib, "Ws2_32.lib")

int main(int argc, char **argv)
{
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
char sendbuf[DEFAULT_BUFLEN];
char recvbuf[DEFAULT_BUFLEN];
int iResult;
int recvbuflen = DEFAULT_BUFLEN;

// Validate the parameters
if (argc != 2) {
printf("usage: %s server-name\n", argv[0]);
while (1);
return 1;
}

// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
while (1);
return 1;
}

ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;

// Resolve the server address and port
iResult = getaddrinfo(argv[1], DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
while (1);
return 1;
}
printf("argv[0] is :%s, argv[1] is: %s\n", argv[0], argv[1]);
// Attempt to connect to an address until one succeeds
for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {

// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
while (1);
return 1;
}

// Connect to server.

iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
printf("socket failed with error\n");
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
printf("i'm going to break\n");
break;
}

freeaddrinfo(result);

if (ConnectSocket == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
while (1);
return 1;
}

// Send an initial buffer
scanf_s(" %s", sendbuf, DEFAULT_BUFLEN);
printf("strlen(sendbuf) is %d, sendbuf is %s\n", strlen(sendbuf), sendbuf);
//sendbuf[strlen(sendbuf)] = '\0';
while (strcmp("!", sendbuf) != 0) {

iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf)+1, 0);
if (iResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
while (1);
return 1;
}

printf("client Sent: %s\n", sendbuf);

// shutdown the connection since no more data will be sent
/*
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
while (1);
return 1;
}
*/
// Receive until the peer closes the connection
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if (iResult > 0)
printf("Client received: %s\n", recvbuf);
scanf_s("%s", sendbuf, DEFAULT_BUFLEN);
//sendbuf[strlen(sendbuf)] = '\0';
}
// cleanup

iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
while (1);
return 1;
}

closesocket(ConnectSocket);
WSACleanup();
while (1);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐