如何实现C#和C++的通信
1个回答
2016-07-23 · 百度知道合伙人官方认证企业
育知同创教育
1【专注:Python+人工智能|Java大数据|HTML5培训】 2【免费提供名师直播课堂、公开课及视频教程】 3【地址:北京市昌平区三旗百汇物美大卖场2层,微信公众号:yuzhitc】
向TA提问
关注
展开全部
只根据题目要求,写了个两种语言(C#,C++)相互通信的代码,主要原理就是socket通信! C++代码(客户端):#include <stdio.h>#include <string.h>#include <AfxWin.h>#include <windows.h>#include "Winsock2.h"#pragma comment (lib, "ws2_32.lib")void main(){ WORD wVersionRequested; WSADATA wsaData; int err; int bytes=0; wVersionRequested = MAKEWORD(1,1); err = WSAStartup( wVersionRequested, &wsaData ); if(err!=0 ) { exit(0); } if(LOBYTE( wsaData.wVersion )!= 1|| HIBYTE( wsaData.wVersion )!= 1) { WSACleanup( ); exit(0); } SOCKET sockClient=socket(AF_INET,SOCK_STREAM,0); SOCKADDR_IN addrSrv; addrSrv.sin_addr.S_un.S_addr=inet_addr("127.0.0.1"); addrSrv.sin_family=AF_INET; addrSrv.sin_port=htons(9950); connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR)); //发送 int i=0; char zjs[10],*buff;; CFile myfile; myfile.Open("牌坊.jpg",CFile::modeRead|CFile::typeBinary);//自己修改图片路径 int t; t=myfile.GetLength(); sprintf(zjs,"%d",t); printf("图片总大小: %s\n",zjs); buff=(char *)malloc((t+1)*sizeof(char)); myfile.Read(buff,myfile.GetLength()); send(sockClient,zjs,strlen(zjs),0); send(sockClient,buff,myfile.GetLength(),0); //接收 char recvBuf[50]; bytes=recv(sockClient,recvBuf,50,0); for(i=0;i<bytes;i++); recvBuf[i]='\0'; printf("%s\n",recvBuf); closesocket(sockClient); WSACleanup();}C#代码(服务端):using System;using System.Collections.Generic;using System.Diagnostics;using System.Text;using System.Text.RegularExpressions;using System.Net;using System.Net.Sockets;using System.IO;namespace socket服务器端{ class Program { static void Main(string[] args) { int bytes=0; byte[] buffer=new byte[10240]; IPEndPoint ipe1 = new IPEndPoint(IPAddress.Any, 9950); Socket socket1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket1.Bind(ipe1); while (true) { socket1.Listen(10); Socket socket2 = socket1.Accept(); IPEndPoint ipe2 = (IPEndPoint)socket2.RemoteEndPoint; if (socket2.Connected) { Console.WriteLine("开始接收..."); int start = 0; FileStream fs = new FileStream("牌坊.jpg",FileMode.Create); BinaryWriter bw = new BinaryWriter(fs); bytes = socket2.Receive(buffer); int total=Int32.Parse(Encoding.Default.GetString(buffer, 0, bytes).ToString()); Console.WriteLine("图片总大小: "+ total); do { bytes = socket2.Receive(buffer); bw.Seek(start, 0); bw.Write(buffer, 0, bytes); start += bytes; Console.WriteLine("已经接收: "+ start); }while(start<total); bw.Flush(); bw.Close(); fs.Close(); socket2.Send(Encoding.Default.GetBytes("主机接收完毕")); } socket2.Shutdown(SocketShutdown.Both); socket2.Close(); break; } Console.WriteLine("接收完毕"); Process.Start("牌坊.jpg"); Console.ReadLine(); } }}注意事项(C++):效果(C++) 效果(C#)
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询