C#与C++如何实现UDP通信

1.背景
两个程序(一个是C#做成的窗体程序,一个是C++做成的窗体程序)
2.问题:
C#与C++如何实现UDP通信??????????求大佬帮忙根据图片显示,做个sample程序,代码中最好能填加上注释(本人没学过这一块内容),求大佬帮帮忙!!!!!!!!!!!!!求帮忙!!!求帮忙!!!
3.想要的效果
左边这个界面上(用C#做成)的TextBox中输入“你好吗?”点击发送,右边的BB界面上(用C++做成)的能显示“你好吗?”,即实现UDP通信
4.相关图片
图片说明

3个回答

c#发送控制台程序代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using System.Net.NetworkInformation;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            string sendString = null;//要发送的字符串  
            byte[] sendData = null;//要发送的字节数组  
            UdpClient client = null;

            IPAddress remoteIP = IPAddress.Parse("127.0.0.1");
            int remotePort = 8080;
            IPEndPoint remotePoint = new IPEndPoint(remoteIP, remotePort);//实例化一个远程端点  

            while (true)
            {
                sendString = Console.ReadLine();
                sendData = Encoding.Default.GetBytes(sendString);

                client = new UdpClient();
                client.Send(sendData, sendData.Length, remotePoint);//将数据发送到远程端点  
                client.Close();//关闭连接  
            }
        }  

    }
}

c++接收控制台代码:

#include <Winsock2.h>
#include <stdio.h>
#pragma  comment(lib, "ws2_32.lib")  
void main(){
    WORD wVersionRequested;
    WSADATA wsaData;
    int err;
    wVersionRequested = MAKEWORD(1, 1);
    err = WSAStartup(wVersionRequested, &wsaData);
    if (err != 0) {
        return;
    }
    if (LOBYTE(wsaData.wVersion) != 1 ||
        HIBYTE(wsaData.wVersion) != 1) {
        WSACleanup();
        return;
    }

    //创建套接字
    SOCKET sockSrv = socket(AF_INET, SOCK_DGRAM, 0);
    //创建地址结构体.
    SOCKADDR_IN addrSrv;
    addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
    addrSrv.sin_family = AF_INET;
    addrSrv.sin_port = htons(6000);
    //绑定套接字和地址.
    bind(sockSrv, (SOCKADDR *)&addrSrv, sizeof(SOCKADDR));
    char recvBuf[100] = {0};
    char sendBuf[100];
    char tempBuf[200];
    SOCKADDR_IN addrClient;
    int len = sizeof(SOCKADDR);
    while (1){
        //接收数据.
        recvfrom(sockSrv, recvBuf, 100, 0, (SOCKADDR *)&addrClient, &len);
        if ('q' == recvBuf[0]){
            sendto(sockSrv, "q", 1, 0, (SOCKADDR *)&addrClient, sizeof(SOCKADDR));
            printf("chat end ! \n");
            break;
        }

        sprintf(tempBuf, "%s say: %s", inet_ntoa(addrClient.sin_addr), recvBuf);
        printf("%s\n", tempBuf);
        printf("please input data:\n");
        gets(sendBuf);
        //发送数据.
        sendto(sockSrv, sendBuf, 100, 0, (SOCKADDR*)&addrClient, sizeof(SOCKADDR));
    }
    //关闭套接字.
    closesocket(sockSrv);
    //关闭套接字库.
    WSACleanup();
}

左边这个界面上(用C#做成)的TextBox中输入“你好吗

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐