用C++建立客户端Socket,怎么用C#建立服务器端Socket进行通信,C++发数据,C#收数据。请给出示例代码。

2011-4-12 09:43

提问者: lisiliang06 | 浏览次数:582次

#include <winsock2.h>
#include <stdio.h>
#include <stdlib.h>#pragma comment(lib, "Ws2_32.lib")#define DEFAULT_BUFLEN 4096
#define DEFAULT_PORT 8000int main(int argc, char* argv[])
{if(argc == 1){printf("Please Input the Address of Input File!\n");return 0;} //Buffersint recvbuflen = DEFAULT_BUFLEN;char sendbuf[DEFAULT_BUFLEN];char recvbuf[DEFAULT_BUFLEN] = "";//FILE FILE* file = fopen("C:/1.txt", "rb");if(file == NULL){printf("Failed to open Input File!\n");return 0 ;}while(1){//SOCKET//----------------------// Declare and initialize variables.int iResult;WSADATA wsaData;// Initialize WinsockiResult = WSAStartup(MAKEWORD(1,1), &wsaData);if (iResult != NO_ERROR){printf("WSAStartup failed with error: %d\n", iResult);return 1;}SOCKET ConnectSocket;struct sockaddr_in clientService; // Create a SOCKET for connecting to serverConnectSocket = socket(AF_INET, SOCK_STREAM, 0)  ;if (ConnectSocket == INVALID_SOCKET){printf("socket failed with error: %ld\n", WSAGetLastError());WSACleanup();continue;}//----------------------// The sockaddr_in structure specifies the address family,// IP address, and port of the server to be connected to.clientService.sin_family = AF_INET;clientService.sin_addr.s_addr = inet_addr( "127.0.0.1" );clientService.sin_port = htons( DEFAULT_PORT );//----------------------// Connect to server.iResult = connect( ConnectSocket, (SOCKADDR*) &clientService, sizeof(clientService) ) ; if (iResult == SOCKET_ERROR) {printf( "connect failed with error: %d\n", WSAGetLastError() );closesocket(ConnectSocket);WSACleanup();continue;}while(1){fread(sendbuf, DEFAULT_BUFLEN,  sizeof(char), file);if(feof(file)){printf("Reading to the end of input file, seek to the beginning of File!\n");fseek(file, 0, SEEK_SET);}//----------------------// Send an initial bufferiResult = send( ConnectSocket, sendbuf, DEFAULT_BUFLEN, 0 );if (iResult == SOCKET_ERROR) {printf("send() failed with error: %d\n", WSAGetLastError());closesocket(ConnectSocket);WSACleanup();break;}else{printf("Send package size = %d \n", iResult);}}if (iResult == SOCKET_ERROR) {continue;}// shutdown the connection since no more data will be sentiResult = shutdown(ConnectSocket, SD_SEND);if (iResult == SOCKET_ERROR) {printf("shutdown failed with error: %d\n", WSAGetLastError());closesocket(ConnectSocket);WSACleanup();return 1;}// cleanupclosesocket(ConnectSocket);WSACleanup();}return 0 ;}

我来帮他解答
2011-4-12 09:51

满意回答

TcpListener进行监听就可以了。
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;class MyTcpListener
{public static void Main(){ TcpListener server=null;   try{// Set the TcpListener on port 13000.Int32 port = 8000;IPAddress localAddr = IPAddress.Parse("127.0.0.1");// TcpListener server = new TcpListener(port);server = new TcpListener(localAddr, port);// Start listening for client requests.server.Start();// Buffer for reading dataByte[] bytes = new Byte[4096];String data = null;// Enter the listening loop.while(true) {Console.Write("Waiting for a connection... ");// Perform a blocking call to accept requests.// You could also user server.AcceptSocket() here.TcpClient client = server.AcceptTcpClient();            Console.WriteLine("Connected!");data = null;// Get a stream object for reading and writingNetworkStream stream = client.GetStream();int i;// Loop to receive all the data sent by the client.while((i = stream.Read(bytes, 0, bytes.Length))!=0) {   // Translate data bytes to a ASCII string.data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);Console.WriteLine("Received: {0}", data);// Process the data sent by the client.data = data.ToUpper();byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);// Send back a response.stream.Write(msg, 0, msg.Length);Console.WriteLine("Sent: {0}", data);            }// Shutdown and end connectionclient.Close();}}catch(SocketException e){Console.WriteLine("SocketException: {0}", e);}finally{// Stop listening for new clients.server.Stop();}Console.WriteLine("\nHit enter to continue...");Console.Read();}
}当然,官方的这个示例是单线程的,一次只能处理一个客户端,你可以将accept到的client扔到一个独立的线程,这样就可以多客户端并发处理了。

tcp communication btw c# and C++相关推荐

  1. dlink中设置端口映射图文讲解(解决电驴tcp链接测试失败问题)

    http://hi.baidu.com/wwt06/item/29d5d5246f3a71d50f37f9f6 dlink中设置端口映射图文讲解(解决电驴tcp链接测试失败问题) 今天找一个资源的时候 ...

  2. ESP8266 RTOS SDK学习之 TCP

    写在前面: 本文章旨在总结备份.方便以后查询,由于是个人总结,如有不对,欢迎指正:另外,内容大部分来自网络.书籍.和各类手册,如若侵权请告知,马上删帖致歉. 本篇就来分析 TCP程序的实现,以及添加自 ...

  3. C语言配置文件解析库——iniparser

    C语言配置文件解析库--iniparser 1. 1.1前言:在对项目的优化时,发现Linux下没有专门的供给C语言使用的配置文件函数,于是搜索到了iniparser库,可以像那些面向对象语言一样,使 ...

  4. 使用Ethereum C++ Aleth客户端创建具有两个同步节点的以太坊Ethereum私有网络

    Creating A Private Network With Two Syncing Nodes 本文是前面两篇文章的延续,链接分别为:Windows10安装Aleth和使用Ethereum C++ ...

  5. python redis链接建立实现分析

    今天在写zabbix storm job监控脚本的时候用到了python的redis模块,之前也有用过,但是没有过多的了解,今天看了下相关的api和源码,看到有ConnectionPool的实现,这里 ...

  6. java 之 网络编程

    网络编程1.网络通讯要素1. IP地址:InetAddress网络中设备的标识.不易记忆,可用主机名.本地回环地址:127.0.0.1 主机名:localhost.2.IPV4数量已经不够分配,所以产 ...

  7. NDC 2010视频下载:看看其他微软平台程序员们都在做什么

    原文地址:<NDC 2010视频下载:看看其他微软平台程序员们都在做什么> NDC(Norwegian Developers Conference,挪威开发者大会)是一年一度的挪威最大的微 ...

  8. 内网端口 转发 穿透 工具简介

    目录 一.LCX 1.lcx 内网端口转发(类似于SSH远程转发-R) 2.本地端口转发(类似于SSH本地转发-L) 二.nc反弹 正向连接 反向连接 三.socks代理工具 (1)Earthworm ...

  9. 端口转发与代理工具 内网代理 内网反弹代理

    目录 一.LCX 二.nc 反弹 三.socks代理工具 四.frp 内网穿透利器 五.ngrok 内网穿透 理论上,任何接入互联网的计算机都是可访问的,但是如果目标主机处于内网,而我们又想和该目标主 ...

最新文章

  1. 触发器与存储过程笔记
  2. java操作字符串——CSDN博客
  3. 数组初始化使用(写)new与不使用(不写)new
  4. C++ new/new operator、operator new、placement new初识
  5. JEECG常见问题大全征集
  6. PHP+SQLite3简约网址导航、书签管理器网站源码
  7. Leetcode 930:和相同的二元子数组
  8. jenkins 持续集成, 使用sbt多项目同时package
  9. DirectAdmin安装mod_encoding支持中文
  10. eof函数怎么用matlab,EOF的源程序MATLAB.doc
  11. 25. (附加)二叉树的所有路径(C++版本)
  12. Neokylin7安装DM8数据库
  13. activemq学习记录(二)(使用p2p模式和使用发布订阅模式去生产以及消费数据)
  14. 【图像隐写】DWT+DCT+PBFO改进图像水印隐藏提取【含GUI Matlab源码 081期】
  15. 以图搜图 - Google 相似图片搜索原理 - Java实现
  16. upc Buy an Integer#二分
  17. 计算机显示丢失d3dcompiler,无法启动此程序提示缺少d3dcompiler文件怎么解决
  18. Vin码/车架号OCr识别
  19. 使用overleaf在线编译latex出现no pdf问题
  20. 微信小程序 JS 遍历对象的属性和值

热门文章

  1. zigbee 定位
  2. 活动回顾(PPT+视频)|Python开发者的年度聚会,我们的现场直击!
  3. 一款高效的程序员画图软件推荐
  4. 餐饮招商加盟高端模版PPT模板
  5. 浙大PTA C语言练习2-11 计算分段函数[2]
  6. 程序员眼中的英语单词
  7. java 游戏 弓箭手 法师 战士_盛世皇城职业选择推荐 战士法师弓箭手哪个厉害
  8. C语言sin函数实现(基于泰勒公式)
  9. 《自动控制原理》PPT例题集合
  10. 【C语言教程】2、C 语言基本语法