I have a server written in C# using a TcpClient and streams. When I try to connect to it and receive data with a C++ application using Winsock, I can receive the data but it has the data but it also displays a bunch of other data. By the way I'm printing to buffer to the console using cout.
If you want to see what the server is supposed to send, go to http://onenetworks.us:12345. There the server will send you a string. For me it sends "16READY" Which is what I'm trying to get my client to only read.
Here's my code, I copied a working code file off of the MSDN page.
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <Ws2tcpip.h>
#include <stdio.h>
#include <iostream>
// Link with ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "12345"
int main() {
//----------------------
// Declare and initialize variables.
WSADATA wsaData;
int iResult;
SOCKET ConnectSocket = INVALID_SOCKET;
struct sockaddr_in clientService;
char *sendbuf = "";
char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;
//----------------------
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != NO_ERROR) {
printf("WSAStartup failed: %d\n", iResult);
return 1;
}
//----------------------
// Create a SOCKET for connecting to server
ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ConnectSocket == INVALID_SOCKET) {
printf("Error at socket(): %ld\n", WSAGetLastError() );
WSACleanup();
return 1;
}
//----------------------
// 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( "199.168.139.14" );
clientService.sin_port = htons( 12345 );
//----------------------
// Connect to server.
iResult = connect( ConnectSocket, (SOCKADDR*) &clientService, sizeof(clientService) );
if ( iResult == SOCKET_ERROR) {
closesocket (ConnectSocket);
printf("Unable to connect to server: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// Send an initial buffer
iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
if (iResult == SOCKET_ERROR) {
printf("send failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("Bytes Sent: %ld\n", iResult);
// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// Receive until the peer closes the connection
do {
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
std::cout << recvbuf <<std::endl;
if ( iResult > 0 )
printf("Bytes received: %d\n", iResult);
else if ( iResult == 0 )
printf("Connection closed\n");
else
printf("recv failed: %d\n", WSAGetLastError());
} while(iResult > 0);
// cleanup
closesocket(ConnectSocket);
WSACleanup();
std::cin.ignore();
//return 0;
}
Print only the characters received, not the entire buffer posted. iResult will contain the length of the data received:
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if ( iResult > 0 )
{
printf("Bytes received: %d\n", iResult);
std::cout << std::string(recvbuf, recvbuf+iResult) <<std::endl;
}
else if ( iResult == 0 )
printf("Connection closed\n");
else
printf("recv failed: %d\n", WSAGetLastError());
The length of your buffer is set to DEFAULT_BUFLEN, so whatever you receive through the socket has that length. you can loop through every char of it, until a value of 0 (or '\0') is found.
You could do something like this:
...
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
recvbuf[iResult] = 0; // add this to zero terminate the receive buffer
std::cout << recvbuf <<std::endl;
...
(of course it assumes iResult is lesser than DEFAULT_BUFLEN)
Related
I want to get the list of available Bluetooth services for any Bluetooth device.
I found BluetoothEnumerateInstalledServices from Windows API, but it enumerates only Installed services. This way I get a list of 3 services instead of 4.
How do I get a list of all services on a Bluetooth device?
I found an one way, but it does not provide full necessary information:
#pragma comment(lib, "ws2_32.lib")
#include <winsock2.h>
#include <Ws2bth.h>
#pragma comment(lib, "Bthprops.lib")
#include <BluetoothAPIs.h>
#include <stdio.h>
#include <iostream>
int main(int argc, char** argv)
{
WSADATA data;
if (WSAStartup(0x0202, &data) != 0)
{
// Выход по ошибке
printf("WSACleanup() failed with error code %ld\n", WSAGetLastError());
return 1;
}
#define BUF_SIZE 10240
WSAQUERYSET* pQuerySet = (WSAQUERYSET*) new BYTE[BUF_SIZE];
ZeroMemory(pQuerySet, BUF_SIZE);
pQuerySet->dwSize = sizeof(WSAQUERYSET);
pQuerySet->dwNameSpace = NS_BTH;
// Запускаем поиск устройств
HANDLE lookupHandle = 0;
int lookupResult = WSALookupServiceBegin(pQuerySet,
LUP_RETURN_NAME | LUP_CONTAINERS | LUP_RETURN_ADDR | LUP_FLUSHCACHE |
LUP_RETURN_TYPE | LUP_RETURN_BLOB | LUP_RES_SERVICE,
&lookupHandle);
if (lookupResult != 0)
{
// Ошибка при инициализации поиска
printf("WSALookupServiceBegin() failed with error code %ld\n", WSAGetLastError());
}
else
{
printf("WSALookupServiceBegin() is OK\n");
}
while (lookupResult == 0)
{
DWORD bufferLen = BUF_SIZE;
lookupResult = WSALookupServiceNext(lookupHandle,
LUP_RETURN_NAME | LUP_RETURN_ADDR,
&bufferLen,
pQuerySet);
if (lookupResult != 0)
break;
DWORD addressLength = 128;
char* addressString = new char[addressLength];
int result = WSAAddressToString(pQuerySet->lpcsaBuffer->RemoteAddr.lpSockaddr,
pQuerySet->lpcsaBuffer->RemoteAddr.iSockaddrLength,
NULL,
(LPWSTR)addressString,
&addressLength);
if (result != 0)
{
printf("\n WSAAddressToString() for remote address failed with error code %ld\n", WSAGetLastError());
}
else {
printf("MAC: ");
printf("%S ", addressString);
printf("Name: ");
wprintf(pQuerySet->lpszServiceInstanceName);
printf("\n");
WSAQUERYSET* pQuerySetServices = (WSAQUERYSET*) new BYTE[BUF_SIZE];
ZeroMemory(pQuerySetServices, BUF_SIZE);
pQuerySetServices->dwSize = sizeof(WSAQUERYSET);
pQuerySetServices->dwNameSpace = NS_BTH;
pQuerySetServices->dwNumberOfCsAddrs = 0;
pQuerySetServices->lpszContext = (LPWSTR)addressString;
pQuerySetServices->lpServiceClassId = (GUID*)&L2CAP_PROTOCOL_UUID;
HANDLE lookupServicesHandle = 0;
int lookupServicesResult = WSALookupServiceBegin(pQuerySetServices, LUP_RETURN_NAME | LUP_RETURN_TYPE | LUP_RES_SERVICE | LUP_RETURN_ADDR | LUP_RETURN_BLOB | LUP_RETURN_COMMENT, &lookupServicesHandle);
if (lookupServicesResult != 0)
{
printf("WSALookupServiceBegin() failed with error code %ld\n", WSAGetLastError());
}
else
{
while (lookupServicesResult == 0)
{
DWORD bufferLen = BUF_SIZE;
lookupServicesResult = WSALookupServiceNext(lookupServicesHandle,
LUP_RETURN_ALL,
&bufferLen,
pQuerySetServices);
if (lookupServicesResult != 0)
break;
GUID guid = *pQuerySetServices->lpServiceClassId;
OLECHAR* guidString;
StringFromCLSID(guid, &guidString);
printf(" ");
wprintf(guidString);
printf(" ");
wprintf(pQuerySetServices->lpszServiceInstanceName);
printf("\n");
}
WSALookupServiceEnd(lookupServicesHandle);
}
}
}
WSALookupServiceEnd(lookupHandle);
WSACleanup();
}
Output:
MAC: (00:1E:B5:8C:64:49) Name: Moga Pro HID
{00000000-0000-0000-0000-000000000000}
{00000000-0000-0000-0000-000000000000} Android Controller Gen-2(ACC)
MAC: (30:39:26:FE:C8:62) Name: SBH20
{00000000-0000-0000-0000-000000000000} Hands-Free unit
{00000000-0000-0000-0000-000000000000} Headset
{00000000-0000-0000-0000-000000000000}
{00000000-0000-0000-0000-000000000000}
{00000000-0000-0000-0000-000000000000}
This method can get a right count of services, but the GUIDs always empty and some services does not have readable name.
I'm working on Client-Server application on Windows. Everything perfect running but when I want to send text (ex: Hello Dude) from C# client to C server then it send just "p" character. I dont know why? Thank you.
C# - Client Codes
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string ip, nick;
int port;
Console.Write("Nick Giriniz : ");
nick = Console.ReadLine();
Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse("192.168.1.37");
System.Net.IPEndPoint remoteEP = new IPEndPoint(ipAdd, 5150);
soc.Connect(remoteEP);
NetworkStream ag = new NetworkStream(soc);
BinaryReader okuyucu = new BinaryReader(ag);
baslangic:
byte[] byData = System.Text.Encoding.ASCII.GetBytes("Hi Dude");
soc.Send(byData);
Console.Write("Wait for answer");
string reply = okuyucu.ReadString();
Console.Write(reply );
goto baslangic;
}
}
}
C - Server
#include <winsock2.h>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <string.h>
#define DEFAULT_PORT 5150
#define AZAMIUZUNLUK 1024
int g_port = DEFAULT_PORT; // Gelen Istekleri Dinleyecek Port
char g_szAddress[128]; // Gelen Istekleri Dinleyecek Arayuz
DWORD WINAPI ClientThread(LPVOID lpParam) //Dword = 32 bit isaretsiz tamsayi.
{
SOCKET sock =(SOCKET)lpParam;
int ret;
char gelenverix[512];
char str[AZAMIUZUNLUK];
for (;;) {
ret = recv(sock, gelenverix, 512, 0); //recv(socket,xxxxx, uzunluk, bayrak);
if (ret == 0)
break;
if (ret == SOCKET_ERROR) {
fprintf(stderr, "Mesajlasma Sona Erdi\n", WSAGetLastError());
break;
}
if (gelenverix == '\x1b')
break;
putchar(gelenverix);
}
return 0;
}
int main(void)
{
WSADATA wsd;
SOCKET sListen,sClient;
int addrSize;
HANDLE hThread;
DWORD dwThreadId;
struct sockaddr_in local, client;
if (WSAStartup(MAKEWORD(2,2), &wsd) != 0) {
fprintf(stderr, "WSAStartup yuklemesi basarisiz!\n");
return 1;
} else {
fprintf(stderr, "WSAStartup Yuklendi!\n");
}
sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
if (sListen == SOCKET_ERROR) {
fprintf(stderr, "Socket Baglantisi Basarisiz!\n", WSAGetLastError());
return 1;
} else {
fprintf(stderr, "Socket Baglantisi Basarili!\n", WSAGetLastError());
}
local.sin_addr.s_addr = htonl(INADDR_ANY); // ip adresimi kullan
local.sin_family = AF_INET; // adres ailesi Arpa Internet protokolu
local.sin_port = htons(g_port); // default port numarasi
if (bind(sListen, (struct sockaddr *)&local, sizeof(local)) == SOCKET_ERROR) {
fprintf(stderr, "bind() failed: %d\n", WSAGetLastError());
return 1;
}
listen(sListen, 8); //8 - cagri kurugunda izin verilen baglanti sayisi
for (;;) {
addrSize = sizeof(client);
sClient = accept(sListen, (struct sockaddr *) &client, &addrSize);
if (sClient == INVALID_SOCKET) {
fprintf(stderr, "accept() failed: %d\n", WSAGetLastError());
break;
}
fprintf(stderr, "Accepted client: %s:%d\n", inet_ntoa(client.sin_addr), ntohs(client.sin_port));
hThread = CreateThread(NULL, 0, ClientThread, (LPVOID)sClient, 0, &dwThreadId);
if (hThread == NULL) {
fprintf(stderr, "CreateThread() failed: %d\n", GetLastError());
break;
}
CloseHandle(hThread);
}
closesocket(sListen);
WSACleanup();
return 0;
}
putchar(gelenverix) should make your compiler yell in pain, as it expects a char and the code passes it a char*.
Use puts() instead. Also make sure gelenverix is 0-terminated beforehand.
ret = recv(sock, gelenverix, 512 - 1, 0); /* One less as you need space to 0-terminate the buffer. */
if (ret == 0)
break;
if (ret == SOCKET_ERROR) {
...
break;
}
gelenverix[ret] = '\0'.
puts(gelenverix);
Or just do
for (size_t i = 0; i < ret; ++i)
{
putchar(gelenverix[i]);
}
I have a TCPListener in C# and the client in Unix C. I use TcpClient.Client.SendFile for transmitting a file to client socket in Unix and it works fine for plain txt file. It fails to produce the full file on the unix end, when I send JPEG files. Any Idea?
C# code part
============
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(10001);
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
Console.WriteLine(" >> Server Started");
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(" >> Accept connection from client");
while ((true))
{
try
{
NetworkStream networkStream = clientSocket.GetStream();
byte[] bytesFrom = new byte[10025];
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom).TrimEnd('\0');
Console.WriteLine(" >> Data from client - " + dataFromClient +" Length "+ dataFromClient.Length);
string a1 = "C:\\MRTD\\PICTURE\\abc.jpg";
clientSocket.Client.SendFile(a1);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadLine();
}
}
}
}
}
Unix C code to read the file
============================
char *tcp_recv( int id_type )
{
register int nbytes;
static char readbuf[MAXLINE];
static char tempbuf[980000];
int ngot = 0, bulk_data=0, p_read_val;
char * x, * y, * z, *j, *k, *x1, *bar;
char bulk_buf[180000], tempstr1[180000] , fstr[40], termtor[40];
int fd_ready;
fd_set read_fds; /* Read file descriptors */
int fd_port = gfd_sock;
struct timeval timeout;
timeout.tv_sec = 3600;
timeout.tv_usec = 0;
while (TRUE)
{
FD_ZERO( &read_fds );
FD_SET( fd_port, &read_fds );
strcpy(fstr,"FAIL");
if((fd_ready = select(fd_port+1,&read_fds,NULL,NULL,&timeout))< 0)
{
if( errno == EINTR ) { continue; }
logmsg("ERROR select() returned errno %d", errno );
logmsg("Select error waiting for packet." );
return fstr;
}
else if( fd_ready == 0 )
{
logmsg("Timeout waiting for packet.");
strcpy(fstr,"TIMEOUT");
return fstr;
}
memset( readbuf, 0x00, sizeof( readbuf ));
memset( br_kde, 0x00, sizeof( br_kde ));
if((nbytes = read( fd_port, readbuf, sizeof(readbuf)-1 )) < 0 )
{
logmsg( "tcp_recv: nbytes %d, errno %d, %s", nbytes, errno, strerror( errno ) );
if (errno == EINTR || errno == EAGAIN )
{
errno = 0;
continue; /* assume SIGCLD */
}
else
{
/*
* connection failer.
*/
logcon( "Desko connection failed. Pier link is DOWN!" );
logmsg( "Desko connection failed. Pier link is DOWN!" );
close_files();
exit (1);
break;
} /* end else if */
}
else
{
logmsg("tcp_recv: readbuf is %s, bytes %d", readbuf, nbytes);
strcat(tempbuf, readbuf);
logmsg("tempbuf is %s", tempbuf );<== full file listing is missing in case of JPEG
}
return tempbuf;
}
}
I have two programs written in c++ and c#.I want to establish a two way communication using named-pipe between them. The C# client program can be connected to the named-pipe created by c++ server program.But nothing received in both ends.
Here is the c++ part (Server):
#include <iostream>
#include <windows.h>
#include <stdlib.h>
#define UNICODE
using namespace std;
HANDLE hnamedPipe = INVALID_HANDLE_VALUE;
BOOL Finished =false;
HANDLE hThread = NULL;
unsigned long __stdcall CS_RcvThr(void * pParam) ;
int main(int argc, char **argv)
{
hnamedPipe = CreateNamedPipe(
"\\\\.\\pipe\\vikeyP",
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_MESSAGE|
PIPE_READMODE_MESSAGE|
PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES,
1024,
1024,
NMPWAIT_USE_DEFAULT_WAIT,
NULL);
if(hnamedPipe == INVALID_HANDLE_VALUE)
{
cout << "Failed" << endl;
}
while (true)
{
cout<< "Waiting for client"<< endl;
if(!ConnectNamedPipe(hnamedPipe,NULL))
{
if(ERROR_PIPE_CONNECTED != GetLastError())
{
cout << "FAIL"<< endl;
}
}
else
{
cout<<"Connected!"<<endl;
hThread = CreateThread( NULL, 0, &CS_RcvThr, NULL, 0, NULL);
if(hThread) cout<<"read thread created"<<endl; else cout<<"cant crat rd thed\n";
break;
}
}
while(1)
{
cout<<"lst loop"<<endl;
//Send over the message
char chResponse[] = "hello\n";
DWORD cbResponse,cbWritten;
cbResponse = sizeof(chResponse);
if (!WriteFile(
hnamedPipe,
chResponse,
cbResponse,
&cbWritten,
NULL))
{
wprintf(L"failiure w/err 0x%08lx\n",GetLastError);
}
cout<<"Sent bytes :)" << endl;
Sleep(10);
}
}
unsigned long __stdcall CS_RcvThr(void * pParam) {
BOOL fSuccess;
char chBuf[100];
DWORD dwBytesToWrite = (DWORD)strlen(chBuf);
DWORD cbRead;
int i;
while (1)
{
fSuccess =ReadFile( hnamedPipe,chBuf,dwBytesToWrite,&cbRead, NULL);
if (fSuccess)
{
printf("C++ App: Received %d Bytes : ",cbRead);
for(i=0;i<cbRead;i++)
printf("%c",chBuf[i]);
printf("\n");
}
if (! fSuccess && GetLastError() != ERROR_MORE_DATA)
{
printf("Can't Read\n");
if(Finished)
break;
}
}
}
Here is the C# part (Client):
private Thread vikeyClientThread;
public void ThreadStartClient()
{
Console.WriteLine("Thread client started ID ={0} name = {1} " ,
Thread.CurrentThread.ManagedThreadId,Thread.CurrentThread.Name);
using (NamedPipeClientStream pipeStream = new NamedPipeClientStream(".", "vikeyP"))
{
// The connect function will indefinately wait for the pipe to become available
// If that is not acceptable specify a maximum waiting time (in ms)
Console.WriteLine("Connecting to ViKEY server...");
pipeStream.Connect();
Console.WriteLine("Connected :)");
//Write from client to server
StreamWriter sw = new StreamWriter(pipeStream);
while (true)
{
//Read server reply
StreamReader sr = new StreamReader(pipeStream);
string temp = "";
sw.WriteLine(System.DateTime.Now);
byte[] c = new byte[200];
temp = sr.ReadLine();
pipeStream.Read(c, 0, c.Length);
Console.WriteLine("RX =:{0}", Encoding.UTF8.GetString(c, 0, c.Length));
Thread.Sleep(500);
}
}
Console.WriteLine("Vikey pipe Closed");
Console.WriteLine("Thread with ID ={0} name = {1} is closed.",
Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.Name);
}
You've set the server side up as a message type vs byte type. If you want to read an arbitrary number of bytes, you'll need to use a byte type named pipe.
You're wrapping the stream in 2 objects one StreamReader and one StreamWriter. Don't do that, just use a Stream. You're trying to read by line, don't do that either. Instead send the number of bytes to read followed by the bytes. On the client side you'll read the byte count then create a buffer big enough then read. If it's text data you then would use an encoder (probably ASCII) to translate it back into a C# string.
Your while(true) should instead detect when the server has closed the pipe.
You should probably look into using an asynchronous named pipe.
Guys I am a not a pro and some of you might think its a basic question but I really need help as I am on deadline to complete my Final Year Project. So here is what I am doing I found two codes a server and a client in which client sends Images to the server over some specified socket. The code is written in C++ and is for Linux. What I am looking for is a way to convert Server side of the code to C# so that I can run it on Windows and client must remain in C++ to be run on Linux. Both these codes are below for referencing.
Server:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
int main ( int agrc, char *argv[] )
{
/******** Program Variable Define & Initialize **********/
int Main_Socket; // Main Socket For Server
int Communication_Socket; // Socket For Special Clients
int Status; // Status Of Function
struct sockaddr_in Server_Address; // Address Of Server
struct sockaddr_in Client_Address;// Address Of Client That Communicate with Server
int Port;
char Buff[100] = "";
Port = atoi(argv[2]);
printf ("Server Communicating By Using Port %d\n", Port);
/******** Create A Socket To Communicate With Server **********/
Main_Socket = socket ( AF_INET, SOCK_STREAM, 0 );
if ( Main_Socket == -1 )
{
printf ("Sorry System Can Not Create Socket!\n");
}
/******** Create A Address For Server To Communicate **********/
Server_Address.sin_family = AF_INET;
Server_Address.sin_port = htons(Port);
Server_Address.sin_addr.s_addr = inet_addr(argv[1]);
/******** Bind Address To Socket **********/
Status = bind ( Main_Socket, (struct sockaddr*)&Server_Address, sizeof(Server_Address) );
if ( Status == -1 )
{
printf ("Sorry System Can Not Bind Address to The Socket!\n");
}
/******** Listen To The Port to Any Connection **********/
listen (Main_Socket,12);
socklen_t Lenght = sizeof (Client_Address);
int yx=1;
char bs[10000] = "??";
while (1)
{
Communication_Socket = accept ( Main_Socket, (struct sockaddr*)&Client_Address, &Lenght );
if (!fork())
{
FILE *fp=fopen("recv.jpg","w");
while(1)
{
char Buffer[10000]="";
if (recv(Communication_Socket, Buffer, sizeof(Buffer), 0))
{
if ( strcmp (Buffer,bs) == 0 )
{
break;
}
else
{
fwrite(Buffer,sizeof(Buffer),1, fp);
printf("\n%d) DATA RECIEVED", yx);
yx=yx+1;
}
}
}
fclose(fp);
send(Communication_Socket, "ACK" ,3,0);
printf("\nACK Send\n");
exit(0);
}
}
return 0;
}
Client:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
int main ( int agrc, char *argv[] )
{
int Socket;
struct sockaddr_in Server_Address;
Socket = socket ( AF_INET, SOCK_STREAM, 0 );
if ( Socket == -1 )
{
printf ("Can Not Create A Socket!");
}
int Port ;
Port = atoi(argv[2]);
Server_Address.sin_family = AF_INET;
Server_Address.sin_port = htons ( Port );
Server_Address.sin_addr.s_addr = inet_addr(argv[1]);
if ( Server_Address.sin_addr.s_addr == INADDR_NONE )
{
printf ( "Bad Address!" );
}
connect ( Socket, (struct sockaddr *)&Server_Address, sizeof (Server_Address) );
FILE *in = fopen("a.jpg","r");
char Buffer[10000] = "";
char bs[10000] = "??";
int len;
int yx=1;
while ((len = fread(Buffer,sizeof(Buffer),1, in)) > 0)
{
send(Socket,Buffer,sizeof(Buffer),0);
printf("\n %d) HELLO DOING IT", yx);
yx = yx + 1;
}
send(Socket,bs,sizeof(Buffer),0);
char Buf[BUFSIZ];
recv(Socket, Buf, BUFSIZ, 0);
if ( strcmp (Buf,"ACK") == 0 )
{
printf("\nRecive ACK\n");
}
close (Socket);
fclose(in);
return 0;
}
P.S. None of these are my own codes they are as I found them on the Internet but they are working perfectly.
Translating socket code from C++ to C# is quite straightforward. Your can do it quite quickly with a near line by line translation. That doesn't take advantage of C# features, but that's easy.
The C# class Socket (documentation) expose the underlying socket API, and you can find the C++ C# equivalent Socket() (constructor), .Bind(), .Listen(), .Accept(), .Receive(), .Send().
For the file IO, you have the File and FileStream classes.