当前位置:文档之家› 文件传输协议的简单设计与实现(c语言.

文件传输协议的简单设计与实现(c语言.

文件传输协议的简单设计与实现(c语言,VC6.0)

使用Socket进行Client/Server程序设计的一般连接过程是这样的:Server端Listen(监听)某个端口是否有连接请求,Client端向Server端发出Connect(连接)请求,Server端向Client端发回Accept(接受)消息。一个连接就建立起来了。Server端和Client端都可以通过Send,Write等方法与对方通信。

对于一个功能齐全的Socket,都要包含以下基本结构,其工作过程包含以下四个基本的步骤:

(1)创建Socket;

(2)打开连接到Socket的输入/出流;

(3)按照一定的协议对Socket进行读/写操作;

(4)关闭Socket.

第三步是程序员用来调用Socket和实现程序功能的关键步骤,其他三步在各种程序中基本相同。

/****************client.c****************/

#include

#include

#include

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

#define DEFAULT_PORT 2302

#define DEFAULT_BUFFER 2048

#define DEFAULT_MESSAGE "This is a test of the emergency \ broadcasting system" char szServerip[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

int dirfun();

int getfun();

int putfun();

int pwdfun();

int cdfun();

int mdfun();

int delfun();

int usafun();

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);

}

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(szServerip, &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;

}

}

}

}

int main(int argc, char**argv)

{

WSADATA wsd;

SOCKET sClient;

char szBuffer[DEFAULT_BUFFER];

int ret;

//unsigned int i;

//int j;

struct sockaddr_in server;

struct hostent *host = NULL;

char choice[5],choice2[40];

// Parse the command line and load Winsock

//

argv[1]="-s:127.0.0.1";

strcpy(szServerip, &argv[1][3]);

//ValidateArgs(argc, argv);

相关主题