I'm a new comer in this stackoverflow.
I successfully sent a file.txt and received it . And I want to send the file through a socket periodically and receive it periodically, too. This is a server client program. Client should send the data and server should receive it with an interval time.
Anyone know how to do this? I used this way:
need to call a function at periodic time intervals in c++
Problem is the file is not sent.
Here is my client code :
void Inwinsock(){
WSAStartup(MAKEWORD(2,2), &winsock);
if (LOBYTE(winsock.wVersion) != 2 || HIBYTE(winsock.wVersion) != 2 ) {
WSACleanup();
}
}
void ClientSock() {
clientSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
ZeroMemory(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
addr.sin_port = htons(6091);
}
int _tmain(int argc, _TCHAR* argv[])
{
Inwinsock();
ClientSock();
start:
if (connect(clientSock, (sockaddr*)&addr, sizeof(addr)) < 0 ) {
Sleep(5000);
goto start;
}
printf("Socket Connected ......... \n");
FILE *File;
char *Buffer;
unsigned long Size;
File = fopen("B:\Filesend.txt","rb");
if(!File){
printf("", WSAGetLastError());
goto END;
}
printf("File open ok ! \n");
fseek(File,0,SEEK_END);
Size = ftell(File);
fseek(File,0,SEEK_SET);
printf("file size succeed...\n");
Buffer = (char*) malloc (Size+1);
fread(Buffer,Size,1,File);
char cisi[10];
sprintf(cisi, "%i", Size);
fclose(File);
printf("sending data....\n");
send(clientSock,cisi,10,0); //file size sent
send(clientSock,Buffer,Size,0); // File Binary sent
free(Buffer);
printf("sending finished....\n");
END:
closesocket(clientSock);
WSACleanup();
getchar();
return 0;
system("PAUSE");
}
and here are my server code :
void iniSocket() {
WSAStartup(MAKEWORD(2,2), &winsock);
if (LOBYTE(winsock.wVersion) != 2 || HIBYTE(winsock.wVersion) != 2) {
WSACleanup();
}
}
void opSock(){
servSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
ZeroMemory(&addr , sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(6091);
bind(servSocket, (sockaddr*)&addr, sizeof(addr));
}
void sockList(){
if (listen(servSocket, 5) == SOCKET_ERROR ) {
printf("listen error %d\n", WSAGetLastError());
}else
{
printf("listen succeed....\n");
}
}
void receive() {
if(recv(ClientAcc,Filesize,10,0)){
Size = atoi((const char*)Filesize);
printf("File size : %d\n",Size);
}
Buffer = (char*)malloc(Size + 1);
int file_dit, total_file = 0 ;
while(total_file < Size)
{
ZeroMemory(Buffer, Size);
if((file_dit = recv(ClientAcc,Buffer,Size,0)) < 0)
{
goto END;
}
else
{
total_file += file_dit;
File = fopen("fileReceived.txt", "wb");
fwrite((const char*)Buffer,1,file_dit,File);
fclose(File);
Sleep(1000);
}
END:
printf("File received \n");
free(Buffer);
closesocket(ClientAcc);
WSACleanup();
getchar();
}
}
int _tmain(int argc, _TCHAR* argv[])
{
while(1)
{
iniSocket();
opSock();
sockList();
if (ClientAcc = accept(servSocket, (sockaddr*)&incommingAddress, &addresslen))
{
char *ClientIP = inet_ntoa(incommingAddress.sin_addr);
int ClientPort = ntohs (incommingAddress.sin_port);
printf("Client connected ....\n" );
printf("IP : %s:%d\n ", ClientIP, ClientPort);
receive();
}
}
return 0;
system("PAUSE");
}
For the periodic part, you could take everything between the start: and END: labels, and put it in a new function, say, sendMyFile();
Then in the client's _tmain(), between the start: and END: labels,
while (1)
{
sendMyFile();
Sleep( 30000 ); // The interval is 30,000.
}
There are certainly better, more sophisticated ways to do something periodically, but this is a good, simple, educational approach.
Related
I'm trying to make a simple heartbeat check from client to server and vice-versa, if connection on either is broken off unexpectedly it prints a message and calls closesocket.
I spent 8 hours on this and it still isn't acceptable to my mentor. Right now I got something that works, but if breakpoint is placed before while loop and connected client is forcefully closed, trying to go past breakpoint causes crash when it should break the loop and write out error.
Server side code:
int main(int argc, char *argv[])
{
SOCKET s, sa;
WSAData oWSAData;
WORD wVersion = 0x0001;
WSAStartup(wVersion, &oWSAData);
s = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in srv_address;
memset(&srv_address, 0, sizeof(srv_address));
srv_address.sin_family = AF_INET;
srv_address.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
srv_address.sin_port = htons(1099);
bind(s, (sockaddr*) &srv_address, sizeof(srv_address));
int l = listen(s, 10);
if (l < 0)
printf("Listen error\n");
else
{
printf("Listen OK. Listening on port %u\n",
htons(srv_address.sin_port));
sa = accept(s, NULL, NULL);
while (true)
{
char buffer[1000];
int nRecvLen = recv(sa, buffer, 999, 0);
buffer[nRecvLen] = '\0';
int r = recv(sa, NULL, 0, 0);
if (r == SOCKET_ERROR && WSAGetLastError() == WSAECONNRESET)
{
printf("Konekcija je naglo prekinuta!\n");
break;
}
else
{
if (nRecvLen > 0)
{
for (int i = 0; i < nRecvLen; i++)
{
cout << buffer[i];
}
}
}
}
closesocket(sa);
closesocket(s);
}
WSACleanup();
return 0;
}
and client side:
int main()
{
SOCKET s;
WSAData oWSAData;
WORD wVersion = 0x0001;
WSAStartup(wVersion, &oWSAData);
s = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in srv_address;
memset(&srv_address, 0, sizeof(srv_address));
srv_address.sin_family = AF_INET;
srv_address.sin_addr.S_un.S_un_b.s_b1 = xxx;
srv_address.sin_addr.S_un.S_un_b.s_b2 = xxx;
srv_address.sin_addr.S_un.S_un_b.s_b3 = x;
srv_address.sin_addr.S_un.S_un_b.s_b4 = xxx;
srv_address.sin_port = htons(1099);
int c = connect(s, (sockaddr*) &srv_address, sizeof(srv_address));
if (c < 0)
{
printf("Connection error\n");
cout << (WSAGetLastError());
}
else
{
string l = "Heartbeat\n";
int p = l.size();
char buff[1000];
strcpy_s(buff, l.c_str());
printf("Connected\n");
while (true)
{
if (send(s, buff, p, 0) > 0)
{
Sleep(1000);
}
else
{
printf("Konekcija je naglo prekinuta\n");
shutdown(s, SD_BOTH);
closesocket(s);
break;
}
}
WSACleanup();
return 0;
}
}
Hi everyone i have a little problem, i supposed to transfer a file from a server( a tcp server with threads to a client). The problems appers at the end of transmision the file is recived by client but it stucks and I can't longer communicate with it.
This is the server
int main(int argc, char *argv[])
{
int socket_desc, client_sock, c;
struct sockaddr_in server, client;
//Create socket
socket_desc = socket(AF_INET, SOCK_STREAM, 0);
if (socket_desc == -1)
{
printf("Could not create socket");
}
puts("Socket created");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(2025);
//Bind
if (bind(socket_desc, (struct sockaddr *) &server, sizeof(server)) < 0)
{
//print the error message
perror("bind failed. Error");
return 1;
}
puts("bind done");
//Listen
listen(socket_desc, 5);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
int enable = 1;
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
pthread_t thread_id;
while ((client_sock = accept(socket_desc,
(struct sockaddr *) &client,
(socklen_t*) &c)))
{
puts("Connection accepted");
if (setsockopt(client_sock,
SOL_SOCKET,
SO_REUSEADDR,
&enable,
sizeof(int)) < 0)
error("setsockopt(SO_REUSEADDR) failed");
if (pthread_create(&thread_id,
NULL,
connection_handler,
(void*) &client_sock) < 0)
{
perror("could not create thread");
return 1;
}
//Now join the thread , so that we dont terminate before the thread
pthread_join(thread_id, NULL);
puts("Handler assigned");
}
if (client_sock < 0)
{
perror("accept failed");
return 1;
}
return 0;
}
void *connection_handler(void *socket_desc)
{
printf("Enter in handler");
//Get the socket descriptor
int sock = *(int*) socket_desc;
send_problemo(sock);
return 0;
}
This is the sending function where I think is the real problem
int send_problemo(int *sock)
{
ssize_t read_return;
char *file_path = "Problems/1.txt";
char buffer[BUFSIZ];
int filefd;
filefd = open(file_path, O_RDONLY);
char end[2] = "1";
if (filefd == -1)
{
perror("open");
exit (EXIT_FAILURE);
}
while (1)
{
read_return = read(filefd, buffer, BUFSIZ);
if (read_return == 0)
{
printf("este 0 \n");
break;
}
if (read_return == -1)
{
perror("read");
exit (EXIT_FAILURE);
}
if (write(sock, buffer, read_return) == -1)
{
perror("write");
exit (EXIT_FAILURE);
}
}
// close(sock);
close(filefd);
}
The client is connecting normally and receives the file in this function
int recive_problemo(int *sockfd)
{
char *file_path = "path.c";
char buffer[BUFSIZ];
ssize_t read_return;
int filefd;
filefd = open(file_path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
if (filefd == -1)
{
perror("open");
exit (EXIT_FAILURE);
}
do
{
read_return = read(sockfd, buffer, BUFSIZ);
if (read_return == -1)
{
perror("read");
exit (EXIT_FAILURE);
}
if (write(filefd, buffer, read_return) == -1)
{
perror("write");
exit (EXIT_FAILURE);
}
} while (read_return > 0);
close(filefd);
}
I kind of managed how to solve this. If i shutdown(SHUT_WR) from server the client isnt stuck anymore, but i want to communicate with it further.
Also with the same function if i transfer from client to server, it works perfectly, so can anyone help me please?
do
{
read_return = read(sockfd, buffer, BUFSIZ);
// error handling
// file write
} while (read_return > 0);
Will keep looping until the socket closes or there's an error. It has no way to tell if a file has finished.
Common solutions are to close the socket (but you don't want that) and establish a communication protocol so that you know when the file is done and can exit the loop.
To keep things very simple, I recommend sending the length of the file before sending the file. The loop now looks something like:
uint64_t file_len;
read_return = recv(sockfd, &file_len, sizeof(file_len), MSG_WAITALL);
if (read_return == sizeof(file_len))
{
// Strongly consider handling the endian of file_len here
while (file_len)
{
size_t readmax = std::min(file_len, BUFSIZ);
read_return = read(sockfd, buffer, readmax);
if (read_return > 0)
{
if (write(filefd, buffer, read_return) == -1)
{
perror("write");
exit (EXIT_FAILURE);
}
file_len -= read_return;
}
else
{
// handle error
// exit loop if not recoverable
}
}
}
The server end picks up the responsibility of getting and sending the length of the file. I won't get into that because there are too many different ways to get the length of a file. Pick your favourite.
Documentation on recv and MSG_WAITALL.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am writing a network client-server program:
Server side:
#include "stdafx.h"
#include <winsock.h>
#include <stdio.h>
#include<stdlib.h>
#define PROTOPORT 5193
#define QLEN 6
#define BUFFERSIZE 512
void ErrorHandler(char *errorMessage)
{
printf(errorMessage);
}
void ClearWinSock()
{
#if defined WIN32
WSACleanup();
#endif
}
int main(int argc, char *argv[])
{
int port;
if (argc > 1)
port = atoi(argv[1]);
else
port = PROTOPORT;
if (port < 0) {
printf("Bad port number %s \n", argv[1]);
return 0;
}
#if defined WIN32
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
ErrorHandler("Error at WSAStartup()\n");
return 0;
}
#endif
//creazione della socket
int MySocket;
MySocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (MySocket < 0) {
ErrorHandler("socket creation failed.\n");
ClearWinSock();
return 0;
}
//ASSEGNAZIONE DI UN INDIRIZZO ALLA SOCKET
struct sockaddr_in sad;
memset(&sad, 0, sizeof(sad)); // ensures that extra bytes contain 0
sad.sin_family = AF_INET;
sad.sin_addr.s_addr = inet_addr("127.0.0.1");
sad.sin_port = htons(port); /* converts values between the host and
network byte order. Specifically, htons() converts 16-bit quantities
from host byte order to network byte order. */
if (bind(MySocket, (struct sockaddr*) &sad, sizeof(sad)) < 0) {
ErrorHandler("bind() failed.\n");
closesocket(MySocket);
ClearWinSock();
return 0;
}
// SETTAGGIO DELLA SOCKET ALL'ASCOLTO
if (listen(MySocket, QLEN) < 0) {
ErrorHandler("listen() failed.\n");
closesocket(MySocket);
ClearWinSock();
return 0;
}
// ACCETTARE UNA NUOVA CONNESSIONE
struct sockaddr_in cad; // structure for the client address
int clientSocket; // socket descriptor for the client
int clientLen; // the size of the client address
printf("Waiting for a client to connect...");
while (1) {
clientLen = sizeof(cad); // set the size of the client address
if ((clientSocket = accept(MySocket, (struct sockaddr *)&cad,
&clientLen)) < 0) {
ErrorHandler("accept() failed.\n");
//RICEZIONE DATI TEST
int bytesRcvd;
int totalBytesRcvd = 0;
int Csocket;
Csocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
char buf[BUFFERSIZE]; // buffer for data from the server
printf("Received: "); // Setup to print the echoed string
if ((bytesRcvd = recv(Csocket, buf, BUFFERSIZE - 1, 0)) <= 0) {
ErrorHandler("recv() failed or connection closed prematurely");
closesocket(Csocket);
ClearWinSock();
return 0;
}
totalBytesRcvd += bytesRcvd; // Keep tally of total bytes
buf[bytesRcvd] = '\0'; // Add \0 so printf knows where to stop
printf("%s", buf); // Print the echo buffer
// CHIUSURA DELLA CONNESSIONE
closesocket(MySocket);
ClearWinSock();
return 0;
}
printf("Handling client %s\n", inet_ntoa(cad.sin_addr));
}
}
and client side:
#include "stdafx.h"
#include <winsock.h>
#include <stdio.h>
#include <stdlib.h>
#define BUFFERSIZE 512
#define PROTOPORT 5193
void ErrorHandler(char *errorMessage) {
printf(errorMessage);
}
void ClearWinSock() {
WSACleanup();
}
int main(void) {
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("error at WSASturtup\n");
return 0;
}
// CREAZIONE DELLA SOCKET
int Csocket;
Csocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (Csocket < 0) {
ErrorHandler("socket creation failed.\n");
closesocket(Csocket);
ClearWinSock();
return 0;
}
// COSTRUZIONE DELL’INDIRIZZO DEL SERVER
struct sockaddr_in sad;
memset(&sad, 0, sizeof(sad));
sad.sin_family = AF_INET;
sad.sin_addr.s_addr = inet_addr("127.0.0.1"); // IP del server
sad.sin_port = htons(5193); // Server port
// CONNESSIONE AL SERVER
if (connect(Csocket, (struct sockaddr *)&sad, sizeof(sad)) < 0)
{
ErrorHandler("Failed to connect.\n");
closesocket(Csocket);
ClearWinSock();
return 0;
}
char* inputString = "prova"; // Stringa da inviare
int stringLen = strlen(inputString); // Determina la lunghezza
// INVIARE DATI AL SERVER
if (send(Csocket, inputString, stringLen, 0) != stringLen) {
ErrorHandler("send() sent a different number of bytes than expected");
closesocket(Csocket);
ClearWinSock();
return 0;
}
// RICEVERE DATI DAL SERVER
int bytesRcvd;
int totalBytesRcvd = 0;
char buf[BUFFERSIZE]; // buffer for data from the server
printf("Received: "); // Setup to print the echoed string
while (totalBytesRcvd < stringLen) {
if ((bytesRcvd = recv(Csocket, buf, BUFFERSIZE - 1, 0)) <= 0) {
ErrorHandler("recv() failed or connection closed prematurely");
closesocket(Csocket);
ClearWinSock();
return 0;
}
totalBytesRcvd += bytesRcvd; // Keep tally of total bytes
buf[bytesRcvd] = '\0'; // Add \0 so printf knows where to stop
printf("%s", buf); // Print the echo buffer
}
// CHIUSURA DELLA CONNESSIONE
closesocket(Csocket);
ClearWinSock();
printf("\n"); // Print a final linefeed
system("pause");
return(0);
}
I have problems in output the string i've passed from client to server: "prova".
Can someone tell me where is error? The code doesn't give me any error.
You are receiving data only when accept failed:
if ((clientSocket = accept(MySocket, (struct sockaddr *)&cad,
&clientLen)) < 0) {
ErrorHandler("accept() failed.\n");
int bytesRcvd;
int totalBytesRcvd = 0;
...
What you need to do is just add a else case:
if ((clientSocket = accept(MySocket, (struct sockaddr *)&cad,
&clientLen)) < 0) {
ErrorHandler("accept() failed.\n");
} else {
int bytesRcvd;
int totalBytesRcvd = 0;
... // receive code here
// clientSocket is the socket to communicate with client
// call recv on it, not the other socket you created in the loop
}
The accept() call returns 'clientSocket', which you promptly ignore and dream up some new 'Csocket' to receive on.
Don't do that.
if ((bytesRcvd = recv(clientSocket, buf, BUFFERSIZE - 1, 0)) <= 0) {
This is the new Server side:
#include "stdafx.h"
#include <winsock.h>
#include <stdio.h>
#include<stdlib.h>
#define PROTOPORT 5193
#define QLEN 6
#define BUFFERSIZE 512
void ErrorHandler(char *errorMessage)
{
printf(errorMessage);
}
void ClearWinSock()
{
#if defined WIN32
WSACleanup();
#endif
}
int main(int argc, char *argv[])
{
int port;
if (argc > 1)
port = atoi(argv[1]);
else
port = PROTOPORT;
if (port < 0) {
printf("Bad port number %s \n", argv[1]);
return 0;
}
#if defined WIN32
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
ErrorHandler("Error at WSAStartup()\n");
return 0;
}
#endif
//creazione della socket
int MySocket;
MySocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (MySocket < 0) {
ErrorHandler("socket creation failed.\n");
ClearWinSock();
return 0;
}
//ASSEGNAZIONE DI UN INDIRIZZO ALLA SOCKET
struct sockaddr_in sad;
memset(&sad, 0, sizeof(sad)); // ensures that extra bytes contain 0
sad.sin_family = AF_INET;
sad.sin_addr.s_addr = inet_addr("127.0.0.1");
sad.sin_port = htons(port); /* converts values between the host and
network byte order. Specifically, htons() converts 16-bit quantities
from host byte order to network byte order. */
if (bind(MySocket, (struct sockaddr*) &sad, sizeof(sad)) < 0) {
ErrorHandler("bind() failed.\n");
closesocket(MySocket);
ClearWinSock();
return 0;
}
// SETTAGGIO DELLA SOCKET ALL'ASCOLTO
if (listen(MySocket, QLEN) < 0) {
ErrorHandler("listen() failed.\n");
closesocket(MySocket);
ClearWinSock();
return 0;
}
// ACCETTARE UNA NUOVA CONNESSIONE
struct sockaddr_in cad; // structure for the client address
int clientSocket; // socket descriptor for the client
int clientLen; // the size of the client address
printf("Waiting for a client to connect...");
while (1) {
clientLen = sizeof(cad); // set the size of the client address
if ((clientSocket = accept(MySocket, (struct sockaddr *)&cad,
&clientLen)) < 0) {
ErrorHandler("accept() failed.\n");
}else{
//RICEZIONE DATI TEST
int bytesRcvd;
int totalBytesRcvd = 0;
char buf[BUFFERSIZE]; // buffer for data from the server
printf("Received: "); // Setup to print the echoed string
if ((bytesRcvd = recv(clientSocket, buf, BUFFERSIZE - 1, 0)) <= 0) {
ErrorHandler("recv() failed or connection closed prematurely");
closesocket(clientSocket);
ClearWinSock();
return 0;
totalBytesRcvd += bytesRcvd; // Keep tally of total bytes
buf[bytesRcvd] = '\0'; // Add \0 so printf knows where to stop
printf("%s", buf); // Print the echo buffer
} Sleep(10);
// CHIUSURA DELLA CONNESSIONE
closesocket(MySocket);
ClearWinSock();
return 0;
}
printf("Handling client %s\n", inet_ntoa(cad.sin_addr));
system("pause");
}
}
I am working on a C++ UDP program, that sends a string to another client and should receive an answer.
Sending works fine, but i cant receive any packets. I looked with wireshark and my computer receives the packet at the right port and from the right IP, but my program seems to ignore them.
Do you have any idea?
int startWinsock(void);
int main()
{
long receive;
SOCKET sock;
char buffer[256];
SOCKADDR_IN si_me;
SOCKADDR_IN si_other;
///////////// Start Winsock ///////////////
receive = startWinsock();
if (receive != 0)
{
printf("Error: startWinsock, error code: %d\n", receive);
return 1;
}
else
{
printf("Winsock started!\n");
}
//////////// Create UDP Socket //////////////
sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sock == INVALID_SOCKET)
{
printf("Fehler: Socket could not be created, errorcode: %d\n", WSAGetLastError());
return 1;
}
else
{
printf("UDP Socket created!\n");
}
si_me.sin_family = AF_INET;
si_me.sin_port = htons(1198);
si_me.sin_addr.s_addr = htonl(INADDR_ANY);
si_other.sin_family = AF_INET;
si_other.sin_port = htons(2000);
si_other.sin_addr.s_addr = inet_addr("10.2.134.10");
receive = connect(sock, (SOCKADDR*)&si_other, sizeof(SOCKADDR));
if (receive == SOCKET_ERROR)
{
cout << "Error : Connection Failed, Errorcode: " << WSAGetLastError() << endl;
}
else
{
cout << "Connected to" << si_other.sin_addr.s_addr << endl;
}
static int timeout = 500;
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));
// char broadcast = 1;
// setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast));
while (1)
{
printf("Insert Text: ");
gets(buffer);
//rc = sendto(s, buf, strlen(buf), 0, (SOCKADDR*)&addr, sizeof(SOCKADDR_IN));
receive = send(sock, buffer, strlen(buffer), 0);
if (receive == SOCKET_ERROR)
{
//printf("error: sendto, error code: %d\n",WSAGetLastError());
printf("Error: send, error code: %d\n", WSAGetLastError());
//return 1;
}
else
{
printf("%d bytes sent!\n", receive);
}
static int timeout = 500;
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));
int wait = 0;
while (wait == 0)
{
//rc = recvfrom(s, buf, 256, 0, (SOCKADDR*)&addr, sizeof(SOCKADDR_IN));
receive = recv(sock, buffer, sizeof(buffer), 0);
if (receive == SOCKET_ERROR)
{
//printf("Fehler: recvfrom, fehler code: %d\n",WSAGetLastError());
printf("Fehler: recv, fehler code: %d\n", WSAGetLastError());
//return 1;
}
else
{
wait = 1;
printf("%d bytes received!\n", receive);
buffer[receive] = '\0';
printf("Received: %s\n", buffer);
}
}
}
getchar();
return 0;
}
int startWinsock(void)
{
WSADATA wsa;
return WSAStartup(MAKEWORD(2, 0), &wsa);
}
To make it so your code works nearly as-is by sending to itself, do the following:
change the "me" port to match "other"... si_me.sin_port = htons( 2000 );
bind to it... bind( sock, (SOCKADDR*)&si_me, sizeof( SOCKADDR ) ); just before connect
As UDP is Datagram-Oriented and connectionless, you need to use recvfrom/sento instead of recv/send. Also the receivetimeout should be set with at timeval.
struct timeval tv;
tv.tv_sec = 5;
tv.tv_usec = 0;
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct timeval));
Im trying to send a image using socket but I have to send the file name as well. Im using a code that i send the file but when I send the file name i receive some strange characters in client.
Client:
#define PORT 20000
#define LENGTH 512
int main(int argc, char *argv[]){
int sockfd;
int nsockfd;
char revbuf[LENGTH];
struct sockaddr_in remote_addr;
/* Get the Socket file descriptor */
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
fprintf(stderr, "ERROR: Failed to obtain Socket Descriptor! (errno = %d)\n",errno);
exit(1);
}
/* Fill the socket address struct */
remote_addr.sin_family = AF_INET;
remote_addr.sin_port = htons(PORT);
inet_pton(AF_INET, "127.0.0.1", &remote_addr.sin_addr);
bzero(&(remote_addr.sin_zero), 8);
/* Try to connect the remote */
if (connect(sockfd, (struct sockaddr *)&remote_addr, sizeof(struct sockaddr)) == -1)
{
fprintf(stderr, "ERROR: Failed to connect to the host! (errno = %d)\n",errno);
exit(1);
}
else
printf("[Client] Connected to server at port %d...ok!\n", PORT);
/* Send File to Server */
//if(!fork())
//{
char* fs_name = "house.jpg";
char sdbuf[LENGTH];
char buffer[256];
int n;
fgets(buffer,255,stdin);
bzero(buffer,256);
n = write(sockfd,buffer, strlen(buffer));
if(n<0) printf("Error: sending filename");
printf("[Client] Sending %s to the Server... ", fs_name);
FILE *fs = fopen(fs_name, "r");
if(fs == NULL)
{
printf("ERROR: File %s not found.\n", fs_name);
exit(1);
}
bzero(sdbuf, LENGTH);
int fs_block_sz;
while((fs_block_sz = fread(sdbuf, sizeof(char), LENGTH, fs)) > 0)
{
if(send(sockfd, sdbuf, fs_block_sz, 0) < 0)
{
fprintf(stderr, "ERROR: Failed to send file %s. (errno = %d)\n", fs_name, errno);
break;
}
bzero(sdbuf, LENGTH);
}
printf("Ok File %s from Client was Sent!\n", fs_name);
//}
close (sockfd);
printf("[Client] Connection lost.\n");
return (0);
}
Part of client that sends the text:
char buffer[256];
int n;
fgets(buffer,255,stdin);
bzero(buffer,256);
n = write(sockfd,buffer, strlen(buffer));
if(n<0) printf("Error: sending filename");
Server:
#define PORT 20000
#define BACKLOG 5
#define LENGTH 512
int main ()
{
int sockfd;
int nsockfd;
int num;
int sin_size;
struct sockaddr_in addr_local; /* client addr */
struct sockaddr_in addr_remote; /* server addr */
char revbuf[LENGTH];
/* Get the Socket file descriptor */
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1 )
{
fprintf(stderr, "ERROR: Failed to obtain Socket Descriptor. (errno = %d)\n", errno);
exit(1);
}
else
printf("[Server] Obtaining socket descriptor successfully.\n");
/* Fill the client socket address struct */
addr_local.sin_family = AF_INET; // Protocol Family
addr_local.sin_port = htons(PORT); // Port number
addr_local.sin_addr.s_addr = INADDR_ANY; // AutoFill local address
bzero(&(addr_local.sin_zero), 8); // Flush the rest of struct
/* Bind a special Port */
if( bind(sockfd, (struct sockaddr*)&addr_local, sizeof(struct sockaddr)) == -1 )
{
fprintf(stderr, "ERROR: Failed to bind Port. (errno = %d)\n", errno);
exit(1);
}
else
printf("[Server] Binded tcp port %d in addr 127.0.0.1 sucessfully.\n",PORT);
/* Listen remote connect/calling */
if(listen(sockfd,BACKLOG) == -1)
{
fprintf(stderr, "ERROR: Failed to listen Port. (errno = %d)\n", errno);
exit(1);
}
else
printf ("[Server] Listening the port %d successfully.\n", PORT);
int success = 0;
while(success == 0)
{
sin_size = sizeof(struct sockaddr_in);
/* Wait a connection, and obtain a new socket file despriptor for single connection */
if ((nsockfd = accept(sockfd, (struct sockaddr *)&addr_remote, &sin_size)) == -1)
{
fprintf(stderr, "ERROR: Obtaining new Socket Despcritor. (errno = %d)\n", errno);
exit(1);
}
else
printf("[Server] Server has got connected from %s.\n", inet_ntoa(addr_remote.sin_addr));
char buffer[256];
bzero(buffer,256);
int n = 0;
n = read(nsockfd, buffer, 255);
if (n < 0) error("ERROR reading from socket");
printf("msg: %s\n",buffer);
/*Receive File from Client */
char* fr_name = "/house.jpg";
FILE *fr = fopen(fr_name, "a");
if(fr == NULL)
printf("File %s Cannot be opened file on server.\n", fr_name);
else
{
bzero(revbuf, LENGTH);
int fr_block_sz = 0;
while((fr_block_sz = recv(nsockfd, revbuf, LENGTH, 0)) > 0)
{
int write_sz = fwrite(revbuf, sizeof(char), fr_block_sz, fr);
if(write_sz < fr_block_sz)
{
error("File write failed on server.\n");
}
bzero(revbuf, LENGTH);
if (fr_block_sz == 0 || fr_block_sz != 512)
{
break;
}
}
if(fr_block_sz < 0)
{
if (errno == EAGAIN)
{
printf("recv() timed out.\n");
}
else
{
fprintf(stderr, "recv() failed due to errno = %d\n", errno);
exit(1);
}
}
printf("Ok received from client!\n");
fclose(fr);
}
}
}
Part of server that receive the text:
char buffer[256];
bzero(buffer,256);
int n = 0;
n = read(nsockfd, buffer, 255);
if (n < 0) error("ERROR reading from socket");
printf("msg: %s\n",buffer);
Need some help with that. Thanks...
In this code in your client:
char buffer[256];
int n;
fgets(buffer,255,stdin);
bzero(buffer,256);
n = write(sockfd,buffer, strlen(buffer));
It looks like you are trying to read the file name from the stdin and send it on the sockfd. But. you zero out the buffer before you send it.