Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /////////////////////////////////////////////////
- // Simple Chat Server, As basic as possibe
- /////////////////////////////////////////////////
- #define _WINSOCKAPI_
- #include <winsock2.h>
- #include <stdio.h>
- #pragma comment(lib, "Ws2_32.lib")
- #define SERVER_PORT 17000
- WSADATA Winsock;
- SOCKET Socket;
- sockaddr_in ServerAddress;
- sockaddr_in IncomingAddress; // Contains the address of the sending client
- sockaddr_in ClientAddress[8]; // Stores the client's addresses
- char Buffer[16];
- int AddressLen = sizeof(IncomingAddress);
- void main()
- {
- WSAStartup(MAKEWORD(2, 2), &Winsock);
- if(LOBYTE(Winsock.wVersion) != 2 || HIBYTE(Winsock.wVersion) != 2)
- {
- WSACleanup();
- return;
- }
- // Make the Socket
- Socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
- // Input server information and bind it to the socket
- ZeroMemory(&ServerAddress, sizeof(ServerAddress));
- ServerAddress.sin_family = AF_INET;
- ServerAddress.sin_port = SERVER_PORT;
- bind(Socket, (sockaddr*)&ServerAddress, sizeof(ServerAddress));
- while(true)
- {
- if(recvfrom(Socket, Buffer, 256, 0, (sockaddr*)&IncomingAddress, &AddressLen))
- {
- // If the packet is a knock, add the client's address to ClientAddress
- if(Buffer[0] == 1)
- {
- for(int i = 0; i < 8; i++)
- {
- if(!ClientAddress[i].sin_family)
- {
- ClientAddress[i] = IncomingAddress;
- break;
- }
- }
- continue;
- }
- // Display the message and broadcast it to all active clients
- Buffer[255] = '\0'; // Always end the packet with this
- printf("Broadcasting: ");
- printf(Buffer);
- printf("\n");
- for(int i = 0; i < 8; i++)
- {
- if(ClientAddress[i].sin_family)
- sendto(Socket, Buffer, 256, 0, (sockaddr*)&ClientAddress[i],
- sizeof(sockaddr));
- }
- // If a client has quit, remove that client's address from ClientAddress
- if(Buffer[0] == ' ')
- {
- for(int i = 0; i < 8; i++)
- {
- if(ClientAddress[i].sin_addr.s_addr == IncomingAddress.sin_addr.s_addr)
- ZeroMemory(&ClientAddress[i], sizeof(sockaddr_in));
- }
- }
- }
- }
- WSACleanup();
- return;
- }
Advertisement
Add Comment
Please, Sign In to add comment