问答1 问答5 问答50 问答500 问答1000
网友互助专业问答平台

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

提问网友 发布时间:2022-04-23 03:50
声明:本网页内容为用户发布,旨在传播知识,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。
E-MAIL:1656858193@qq.com
2个回答
热心网友 回答时间:2023-09-20 20:38

跟光磊学Java-HelloWorld程序开发

热心网友 回答时间:2023-09-20 20:39
/*分别编译client.c server.c*/

/*use*/
/*1.先运行server*/
/*D:\>client /? */
/*2. D:\>client -p:5150 -s:192.168.99.77 -n:5 */

/*server.c*/
// Mole 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, don't echo the data back
//
#include <winsock2.h>

#include <stdio.h>
#include <stdlib.h>
#pragma comment (lib,"ws2_32.lib")
#define DEFAULT_PORT 5150
#define DEFAULT_BUFFER 4096

int iPort = DEFAULT_PORT; // Port to listen for clients on
BOOL bInterface = FALSE, // Listen on the specified interface
bRecvOnly = FALSE; // Receive data only; don't echo back
char szAddress[128]; // Interface to listen for clients on

//
// Function: usage
//
// Description:
// Print usage information and exit
//
void 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 Don't 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 perform
//
void ValidateArgs(int argc, char **argv)
{
int i;

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]);
break;
case 'i':
bInterface = TRUE;
if (strlen(argv[i]) > 3)
strcpy(szAddress, &argv[i][3]);
break;
case 'o':
bRecvOnly = TRUE;
break;
default:
usage();
break;
}
}
}
}

//
// 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,
nLeft,
idx;

while(1)
{
// Perform a blocking recv() call
//
ret = recv(sock, szBuff, DEFAULT_BUFFER, 0);
if (ret == 0) // Graceful close
break;
else if (ret == SOCKET_ERROR)
{
printf("recv() failed: %d\n", WSAGetLastError());
break;
}
szBuff[ret] = '\0';
printf("RECV: '%s'\n", szBuff);
//
// If we selected to echo the data back, do it
//
if (!bRecvOnly)
{
nLeft = ret;
idx = 0;
//
// Make sure we write all the data
//
while(nLeft > 0)
{
ret = send(sock, &szBuff[idx], nLeft, 0);
if (ret == 0)
break;
else if (ret == SOCKET_ERROR)
{
printf("send() failed: %d\n",
WSAGetLastError());
break;
}
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 socket
//
sListen = 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 it
//
if (bInterface)
{
local.sin_addr.s_addr = inet_addr(szAddress);
if (local.sin_addr.s_addr == INADDR_NONE)
usage();
}
else
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());
break;
}
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());
break;
}
CloseHandle(hThread);
}
closesocket(sListen);

WSACleanup();
return 0;
}

/*client.c*/

// Mole 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 Server's IP address or hostname
// -n:x Number of times to send message
// -o Send messages only; don't receive
//
#include <winsock2.h>
#include <stdio.h>
#include <stdlib.h>
#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 to
szMessage[1024]; // Message to send to sever
int iPort = DEFAULT_PORT; // Port on server to connect to
DWORD dwCount = DEFAULT_COUNT; // Number of times to send message
BOOL bSendOnly = FALSE; // Send data only; don't receive

//
// Function: usage:
//
// Description:
// Print usage information and exit
//
void 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 Server's IP address or hostname\n");
printf(" -n:x Number of times to send message\n");
printf(" -o Send messages only; don't receive\n");
ExitProcess(1);
}

//
// Function: ValidateArgs
//
// Description:
// Parse the command line arguments, and set some global flags
// to indicate what actions to perform
//
void ValidateArgs(int argc, char **argv)
{
int i;

for(i = 1; i < argc; i++)
{
if ((argv[i][0] == '-') || (argv[i][0] == '/'))
{
switch (tolower(argv[i][1]))
{
case 'p': // Remote port
if (strlen(argv[i]) > 3)
iPort = atoi(&argv[i][3]);
break;
case 's': // Server
if (strlen(argv[i]) > 3)
strcpy(szServer, &argv[i][3]);
break;
case 'n': // Number of times to send message
if (strlen(argv[i]) > 3)
dwCount = atol(&argv[i][3]);
break;
case 'o': // Only send message; don't receive
bSendOnly = TRUE;
break;
default:
usage();
break;
}
}
}
}

//
// 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,
i;
struct sockaddr_in server;
struct hostent *host = NULL;

// Parse the command line and load Winsock
//
ValidateArgs(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 server
//
sClient = 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 wasn't in the form
// "aaa.bbb.ccc.ddd" it's a hostname, so try to resolve it
//
if (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 data
//
for(i = 0; i < dwCount; i++)
{
ret = send(sClient, szMessage, strlen(szMessage), 0);
if (ret == 0)
break;
else if (ret == SOCKET_ERROR)
{
printf("send() failed: %d\n", WSAGetLastError());
break;
}
printf("Send %d bytes\n", ret);
if (!bSendOnly)
{
ret = recv(sClient, szBuffer, DEFAULT_BUFFER, 0);
if (ret == 0) // Graceful close
break;
else if (ret == SOCKET_ERROR)
{
printf("recv() failed: %d\n", WSAGetLastError());
break;
}
szBuffer[ret] = '\0';
printf("RECV [%d bytes]: '%s'\n", ret, szBuffer);
}
}
closesocket(sClient);

WSACleanup();
return 0;
}

本文如未解决您的问题请添加抖音号:51dongshi(抖音搜索懂视),直接咨询即可。

控制台程序如何进行网络编程? 常用的网络编程语言有哪些? 在哪些场景需要应用网络编程? 网络程序与一般的单机环境运行的程序有何不同? 程序设计和网络编程有什么区别,分别包括哪些内容? 黑裤子不小心被八四滴了几滴,怎么办? 我的一条黑色休闲裤不小心溅上了一滴502胶水,后来变硬了。有什么好方法可以除去?不损害裤子 黑色裤子沾到别的颜色的东西,洗不掉怎么办 我的黑裤子不小心滴了几滴84消毒液 现在变成几个小黄点 那条裤子太好了 不忍心扔掉 怎么办啊 有什么办法 黑色的裤子不小心洒到有漂白水变色了怎么办?可以恢复原样吗? 黑色的裤子不小心滴上了84消毒液,裤子有一块变红了,怎么办? 黑裤子不小心洒上84褪色了,怎么补救? 黑裤子滴上油了 怎么能洗干净 黑色裤子不小心滴了几点84消毒液,变红了怎么回事 84消毒液不小心溅到黑色裤子上了,怎么办 黑色裤子不小心滴了几点84消毒液,变红了怎么回事? 黑裤子上面不小心滴上洗衣液,洗完后裤子的那个地方发白怎么办? 黑色裤子上面滴了84怎么处理 黑色裤子,不小心滴上了84消毒液,变成红色,怎么才能恢复原色? 穿着黑色裤子,不小心滴上了84消毒液,变成红色,用啥洗能恢复原色?_百度... 黑色衣服不小心滴上84。褪色如何处理? 网络应用程序设计是指什么? c程序如何在windows下进行网络编程? Java程序设计之网络编程的内容简介 什么是网络程序? java网络编程的基本内容有哪些?其特点和优势如何?请进行论述。_百度知 ... 网络编程是什么东西,它跟我学习C++,windowsAPI还有MFC有什么关系,网络编程我都不知道是什么东西 网络编程一般用什么语言实现? 学习网络编程和编写应用程序哪个简单更有前途?(用C#) java网络编程:程序问题,接收不到数据 网络编程方面的,最好是java的 NBA中的双塔是什么? NBA历史上最强的双塔组合是谁?当年他们的实力到底有多强? NBA历史上有哪些实力强劲的内线双塔组合? 什么是nba双塔组合 篮球中的双塔是什么意思 李慕豪和范子铭的双塔组合为首钢取得不错的战绩,他们的默契是如何形成的? 什么是双塔阵容?? 双塔组合为什么不参加汤姆斯杯 微信怎么群发红包?给所有好友发红包。 首钢双塔组合为首钢先后战胜广东与浙江,你如何评价李慕豪和范子铭的双塔?
Top