socket编程实现客户端向服务器端发消息

服务器端代码

#include <stdio.h>
#include <stdlib.h>
#include <WinSock2.h>
#include <cstring>
#pragma comment(lib, "ws2_32.lib")  //加载 ws2_32.dll


int main()
{
    WSADATA wsadata;
    WSAStartup( MAKEWORD(2, 2),&wsadata);

    SOCKET mysocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);

    SOCKADDR_IN myaddr;
    memset(&myaddr,0,sizeof(myaddr));
    myaddr.sin_family = AF_INET;
    myaddr.sin_port = htons(1234);
    myaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    connect(mysocket,(SOCKADDR*)&myaddr,sizeof(SOCKADDR));
    char buffer[1000];
    //cin>>buffer;
    scanf("%s",buffer);
    send(mysocket,buffer,1000,0);

    closesocket(mysocket);
    //终止使用 DLL
    WSACleanup();
    system("pause");
    return 0;
}

客户端代码

#include <iostream>
#include <stdio.h>
#include <winsock2.h>
#pragma comment (lib, "ws2_32.lib")  //加载 ws2_32.dll
using namespace std;

int main()
{
    WSADATA wsadata;
    WSAStartup( MAKEWORD(2, 2),&wsadata);

    SOCKET mysocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);

    sockaddr_in myaddr;
    myaddr.sin_family = AF_INET;
    myaddr.sin_port = htons(1234);
    myaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    bind(mysocket,(SOCKADDR*)&myaddr,sizeof(SOCKADDR));

    listen(mysocket,5);

    SOCKADDR getclient;
    int nsize = sizeof(SOCKADDR);
    SOCKET clientsocket = accept(mysocket,(SOCKADDR*)&getclient,&nsize);
    char buffer[1000];
    int length = recv(clientsocket,buffer,1000,0);
    //send(clientsock,buffer,1000,0);
    printf("%s\n",buffer);

    closesocket(clientsocket);
    closesocket(mysocket);

    WSACleanup();
    system("pause");
    return 0;
}

 

转载于:https://www.cnblogs.com/simplekinght/p/8646130.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值