tcp communication btw c# and C++
2012-05-15 15:55
567 查看
用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 8000 int main(int argc, char* argv[]) { if(argc == 1) { printf("Please Input the Address of Input File!\n"); return 0; } //Buffers int 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 Winsock iResult = 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 server ConnectSocket = 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 buffer iResult = 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 sent iResult = shutdown(ConnectSocket, SD_SEND); if (iResult == SOCKET_ERROR) { printf("shutdown failed with error: %d\n", WSAGetLastError()); closesocket(ConnectSocket); WSACleanup(); return 1; } // cleanup closesocket(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 data Byte[] 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 writing NetworkStream 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 connection client.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扔到一个独立的线程,这样就可以多客户端并发处理了。
相关文章推荐
- c++ send tcp ___ server c# byte转结构
- Differences Between C++ Templates and C# Generics (C# Programming Guide)
- A question about C++ static method and C# static method
- VB.NET/C# and JavaScript communication
- Call C# Code from C++ and read an array of struct which contains strings
- C#:TcpClient(客户端) and TcpServer(服务端)
- Differences Between C++ Templates and C# Generics
- C# p/invoke: marshaling class between C# and C++ class
- [原] bit block transfer (bitBlt) c# , vb and c++cli Implementation
- socket communication between a Java and/or C++ programs (现成的程序)
- Simple TCP Socket Client and Server Communication in C Under Linux
- Visual Studio 2017 + C# + C++ and swig
- process communication by using pipe and tcp
- Create a C++ DLL and Use It in C# (P/Invoke)
- 引用、指针、抽象类的多态 in C++ and C#
- C C++ and C#
- Interop(交互) Between C# and C++ 研究一
- How to call c++ exported method and classes in c#
- Interop(交互) Between C# and C++ 研究一
- SOCKET Communication writen in C# (3) TcpListener 和TcpClient 异步非阻塞