基于TCP的socket简易聊天程序(服务端和客户端)

基于TCP的socket程序服务端和客户端,基本要求:客户端能发送消息到服务端,服务端再把此消息返回给客户端。

1.1服务端:

        (1). 初始化WSA,构建一个Socket,指定本地的端口,用于监听其连接请求。

     (2).调用socket的accept()方法获得客户端的连接请求,建立与客户端的连接。

     (3).进行数据的写入和读出。

(4).调用closesocket()方法关闭socket连接 。



#include "stdafx.h"
#include 
#include   //WINSOCK.H(这个是WINSOCK API的头文件,WIN2K以上支持WINSOCK2,所以 
					   //可以用WINSOCK2.H); 

#pragma comment(lib, "WS2_32.lib")//Ws2_32.lib(WINSOCK API连接库文件).

#define BUF_SIZE 1024

int main(int argc, char* argv[])
{
	WSADATA wsaData;
    SOCKET  socketL;  // socket for listening
    SOCKET  socketC;  // socket for Communication
    SOCKADDR_IN serverAddr;
    int nRet = -1;
	char temp[4] = "bey";
    char recvbuf[BUF_SIZE];
	char sendbuf[BUF_SIZE];

    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
    {
        printf("WSAStartup failed!\n");
        return 1;
    }
	
    socketL = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    serverAddr.sin_family      = AF_INET;
    serverAddr.sin_port        = htons(5678);
    serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);

    bind(socketL, (SOCKADDR*)&serverAddr, sizeof(serverAddr));
    listen(socketL, 5);
    socketC = accept(socketL, NULL, NULL);
	printf("请输入bey结束聊天");
    if (socketC != INVALID_SOCKET)
    {
		while(1)
		{
			nRet = recv(socketC, recvbuf, sizeof(recvbuf), 0);
			if (nRet > 0)
				printf("%s \n", recvbuf);
			scanf("%s",sendbuf);
			send(socketC, sendbuf,sizeof(sendbuf), 0);
			if(strcmp(sendbuf,temp) == 0 || strcmp(recvbuf,temp) == 0)
		{
			break;
		}
		}
		
    }

    closesocket(socketC);
    closesocket(socketL);	
    WSACleanup();

	printf("聊天结束");
	getchar();
	return 0;
}

 

客户端

        (1)初始化WSA,建立一个SOCKET,;

        (2)连接到服务器;

        (3)发送和接受数据;

        (4)调用closesocket()方法关闭socket连接 。



#include "stdafx.h"
#include 
#include 
#pragma comment(lib, "WS2_32.lib")
#define BUF_SIZE 1024
int main(int argc, char* argv[])
{
	WSADATA wsaData;
    SOCKADDR_IN serverAddr;
    SOCKET socketC;
	int nRet = -1;
	char temp[4] = "bey";
    char sendbuf[BUF_SIZE];
	char recvbuf[BUF_SIZE];
     if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
    {
        printf("WSAStartup failed!\n");
        return 1;
    }
    socketC = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(5678);
    serverAddr.sin_addr.s_addr = inet_addr("172.16.180.51");//这里的ip为目的地址(服务端地址)
    connect(socketC, (SOCKADDR*)&serverAddr, sizeof(serverAddr));
	printf("请输入bey结束聊天");
	while(1)
	{
		scanf("%s",sendbuf);
		send(socketC, sendbuf,sizeof(sendbuf), 0);
		nRet = recv(socketC, recvbuf, sizeof(recvbuf), 0);
		if (nRet > 0)
			printf("%s\n", recvbuf);
		if(strcmp(sendbuf,temp) == 0 || strcmp(recvbuf,temp) == 0)
		{
			break;
		}
	}

    closesocket(socketC);

    WSACleanup();

	printf("聊天结束");
	getchar();
	return 0;
}

 

你可能感兴趣的:(网络编程)