SOCKET网络编程游戏(Socket网络编程)

2023-12-26 08:48:17 数码极客 bianji01

 

socket网络编程,写一个Helloworld程序

跟光磊学Java-HelloWorld程序开发/*分别编译client.c server.c*//*use*//*1.先运行server*//*D:\>client /? *//*2. D:\>client -p:5150 -s:192.168.99.77 -n:5 *//*server.c*/// Module Name: Server.c// Description:// This example illustrates a simple TCP server that accepts// incoming client connections. Once a client connection is// established, a thread is spawned to read data from the// client and echo it back (if the echo option is not// disabled).// Compile:// cl -o Server Server.c ws2_32.lib// Command line options:// server [-p:x] [-i:IP] [-o]// -p:x Port number to listen on// -i:str Interface to listen on// -o Receive only, dont echo the data back#include #include #include #pragma comment (lib,"ws2_32.lib")#define DEFAULT_PORT 5150#define DEFAULT_BUFFER 4096int iPort = DEFAULT_PORT; // Port to listen for clients onBOOL bInterface = FALSE, // Listen on the specified interfacebRecvOnly = FALSE; // Receive data only; dont echo backchar szAddress[128]; // Interface to listen for clients on// Function: usage// Description:// Print usage information and exitvoid usage()printf("usage: server [-p:x] [-i:IP] [-o]\n\n");printf(" -p:x Port number to listen on\n");printf(" -i:str Interface to listen on\n");printf(" -o Dont echo the data back\n\n");ExitProcess(1);// Function: ValidateArgs// Description:// Parse the command line arguments, and set some global flags// to indicate what actions to performvoid ValidateArgs(int argc, char **argv)for(i = 1; i < argc; i++)if ((argv[i][0] == -) || (argv[i][0] == /))switch (tolower(argv[i][1]))case p:iPort = atoi(&argv[i][3]);case i:bInterface = TRUE;if (strlen(argv[i]) > 3)strcpy(szAddress, &argv[i][3]);case o:bRecvOnly = TRUE;default:usage();// Function: ClientThread// Description:// This function is called as a thread, and it handles a given// client connection. The parameter passed in is the socket// handle returned from an accept() call. This function reads// data from the client and writes it back.DWORD WINAPI ClientThread(LPVOID lpParam)SOCKET sock=(SOCKET)lpParam;char szBuff[DEFAULT_BUFFER];int ret,while(1)// Perform a blocking recv() callret = recv(sock, szBuff, DEFAULT_BUFFER, 0);if (ret == 0) // Graceful closeelse if (ret == SOCKET_ERROR)printf("recv() failed: %d\n", WSAGetLastError());szBuff[ret] = \0;printf("RECV: %s\n", szBuff);// If we selected to echo the data back, do itif (!bRecvOnly)nLeft = ret;idx = 0;// Make sure we write all the datawhile(nLeft > 0)ret = send(sock, &szBuff[idx], nLeft, 0);if (ret == 0)else if (ret == SOCKET_ERROR)printf("send() failed: %d\n",WSAGetLastError());nLeft -= ret;idx += ret;return 0;// Function: main// Description:// Main thread of execution. Initialize Winsock, parse the// command line arguments, create the listening socket, bind// to the local address, and wait for client connections.int main(int argc, char **argv)WSADATA wsd;SOCKET sListen,sClient;int iAddrSize;HANDLE hThread;DWORD dwThreadId;struct sockaddr_in local,client;ValidateArgs(argc, argv);if (WSAStaRTUp(MAKEWORD(2,2), &wsd) != 0)printf("Failed to lOAd Winsock!\n");return 1;// Create our listening socketsListen = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);if (sListen == SOCKET_ERROR)printf("socket() failed: %d\n", WSAGetLastError());return 1;// Select the local interface and bind to itif (bInterface)local.sin_addr.s_addr = inet_addr(szAddress);if (local.sin_addr.s_addr == INADDR_NONE)usage();local.sin_addr.s_addr = htonl(INADDR_ANY);local.sin_family = AF_INET;local.sin_port = htons(iPort);if (bind(sListen, (struct sockaddr *)&local,sizeof(local)) == SOCKET_ERROR)printf("bind() failed: %d\n", WSAGetLastError());return 1;listen(sListen, 8);// In a continous loop, wait for incoming clients. Once one// is detected, create a thread and pass the handle off to it.while (1)iAddrSize = sizeof(client);sClient = accept(sListen, (struct sockaddr *)&client,&iAddrSize);if (sClient == INVALID_SOCKET)printf("accept() failed: %d\n", WSAGetLastError());printf("Accepted client: %s:%d\n",inet_ntoa(client.sin_addr), ntohs(client.sin_port));hThread = CreateThread(NULL, 0, ClientThread,(LPVOID)sClient, 0, &dwThreadId);if (hThread == NULL)printf("CreateThread() failed: %d\n", GetLastError());CloseHandle(hThread);closesocket(sListen);WSACleanup();return 0;/*client.c*/// Module Name: Client.c// Description:// This sample is the echo client. It connects to the TCP server,// sends data, and reads data back from the server.// Compile:// cl -o Client Client.c ws2_32.lib// Command Line Options:// client [-p:x] [-s:IP] [-n:x] [-o]// -p:x Remote port to send to// -s:IP Servers IP address or hostname// -n:x Number of times to send message// -o Send messages only; dont receive#include #include #include #pragma comment (lib,"ws2_32.lib")#define DEFAULT_COUNT 20#define DEFAULT_PORT 5150#define DEFAULT_BUFFER 2048#define DEFAULT_MESSAGE "hello world"char szServer[128], // Server to connect toszMessage[1024]; // Message to send to severint iPort = DEFAULT_PORT; // Port on server to connect toDWORD dwCount = DEFAULT_COUNT; // Number of times to send messageBOOL bSendOnly = FALSE; // Send data only; dont receive// Function: usage:// Description:// Print usage information and exitvoid usage()printf("usage: client [-p:x] [-s:IP] [-n:x] [-o]\n\n");printf(" -p:x Remote port to send to\n");printf(" -s:IP Servers IP address or hostname\n");printf(" -n:x Number of times to send message\n");printf(" -o Send messages only; dont receive\n");ExitProcess(1);// Function: ValidateArgs// Description:// Parse the command line arguments, and set some global flags// to indicate what actions to performvoid ValidateArgs(int argc, char **argv)for(i = 1; i < argc; i++)if ((argv[i][0] == -) || (argv[i][0] == /))switch (tolower(argv[i][1]))case p: // Remote portif (strlen(argv[i]) > 3)iPort = atoi(&argv[i][3]);case s: // Serverif (strlen(argv[i]) > 3)strcpy(szServer, &argv[i][3]);case n: // Number of times to send messageif (strlen(argv[i]) > 3)dwCount = atol(&argv[i][3]);case o: // Only send message; dont receivebSendOnly = TRUE;default:usage();// Function: main// Description:// Main thread of execution. Initialize Winsock, parse the// command line arguments, create a socket, connect to the// server, and then send and receive data.int main(int argc, char **argv)WSADATA wsd;SOCKET sClient;char szBuffer[DEFAULT_BUFFER];int ret,struct sockaddr_in server;struct hostent *host = NULL;// Parse the command line and load WinsockValidateArgs(argc, argv);if (WSAStartup(MAKEWORD(2,2), &wsd) != 0)printf("Failed to load Winsock library!\n");return 1;strcpy(szMessage, DEFAULT_MESSAGE);// Create the socket, and attempt to connect to the serversClient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);if (sClient == INVALID_SOCKET)printf("socket() failed: %d\n", WSAGetLastError());return 1;server.sin_family = AF_INET;server.sin_port = htons(iPort);server.sin_addr.s_addr = inet_addr(szServer);// If the supplied server address wasnt in the form// "aaa.bbb.ccc.ddd" its a hostname, so try to resolve itif (server.sin_addr.s_addr == INADDR_NONE)host = gethostbyname(szServer);if (host == NULL)printf("Unable to resolve server: %s\n", szServer);return 1;CopyMemory(&server.sin_addr, host->h_addr_list[0],host->h_length);if (connect(sClient, (struct sockaddr *)&server,sizeof(server)) == SOCKET_ERROR)printf("connect() failed: %d\n", WSAGetLastError());return 1;// Send and receive datafor(i = 0; i < dwCount; i++)ret = send(sClient, szMessage, strlen(szMessage), 0);if (ret == 0)else if (ret == SOCKET_ERROR)printf("send() failed: %d\n", WSAGetLastError());printf("Send %d bytes\n", ret);if (!bSendOnly)ret = recv(sClient, szBuffer, DEFAULT_BUFFER, 0);if (ret == 0) // Graceful closeelse if (ret == SOCKET_ERROR)printf("recv() failed: %d\n", WSAGetLastError());szBuffer[ret] = \0;printf("RECV [%d bytes]: %s\n", ret, szBuffer);closesocket(sClient);WSACleanup();return 0;

socket网络编程

客户端与服务端通过socket套字节连接后都会返回一个实例对象,分别保存这个对象,就相当于保存的对方的地址。不同的客户端连接到服务器,得到的对象都是不同的。服务端要发信息直接拿这个对象进行操作就可以了。

很久没写了,具体名称记不起来了,思路就是这样的

你好,我是用Listlist=newList();保存对象的,但我不知道怎么根据不同的客户发送不同的信息来告诉客户端已经成功连接服务器了!,有这样的项目么发个给我看看...

这个就要靠你自定义的协议了啊,比如你定义登录时客户端发送“denglu_id”到服务端来登录,服务端接收后解析知道是客户端要登录,就保存套字节对象并用这个对象给客户端返回值

socket 可以 制作实时的网络游戏吗

你好 先去手机上下载游戏发展国和动画公司物语 制作一个游戏需要的人力物力自己研究一下

socket网络编程

服务器与每一个客户端建立连接,就多了一个线程,通过对线程的名字和Socket对象来进行处理,保存到hasmap.写一个遍历hasmap可以得到每个客服的Socket,这样就可以发送到各个客服端了!

声明:易趣百科所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系315127732@qq.com
广告位招租
横幅广告