[Resolvido] Socket Send - Recv
Oi, eu estou tendo problemas com um simples server e um simples cliente.
Os 2 compilam, mas não consigo estabelecer conexão entre eles. Se alguem souber onde esta o erro por favor me fale. Desde ja agradeço a paciência :lol:/>.
// CLIENTE.C ####
#include <stdio.h>
#include <winsock.h>
#include <conio.h>
#include <windows.h>
#include <string.h>
WSADATA data;
SOCKET winsock;
SOCKADDR_IN sock;
int main()
{
char buffer[1024];
char buffer2[1024];
int bytes;
if(WSAStartup(MAKEWORD(1,1),&data) == SOCKET_ERROR)
{
printf("Erro ao inicializar o winsock");
getch();
return 0;
}
if((winsock = socket(AF_INET,SOCK_STREAM,0)) == SOCKET_ERROR)
{
printf("Erro ao criar socket");
getch();
return 0;
}
printf("Socket iniciado!!!\n");
sock.sin_family= AF_INET;
sock.sin_port = htons(8080);
sock.sin_addr.s_addr = inet_addr("187.7.150.109");
if(connect(winsock,(SOCKADDR*)&sock,sizeof(sock)) == SOCKET_ERROR){
printf("Erro ao se conectar!!!\n");
getch();
return 0;
}
printf("Conexao estabelecida!!!\n");
while(1){
Sleep(1);
printf("Para: ");
gets(buffer);
strcat(buffer,"\r\n");
send(winsock, buffer, strlen(buffer), 0);
printf("\n");
memset(buffer2, 0, 1024);
bytes = recv(winsock, buffer2, 1024, 0); // Não estou recebendo nada do server ...
getch();
if(bytes == -1){ // SEMPRE ENTRA NESSE IF
printf("Conexao perdida!!!\n");...
closesocket(winsock);
WSACleanup();
getch();
return 0;
}
printf("De: %s", buffer2);
printf("\n");
}
closesocket(winsock);
WSACleanup();
return 0;
}
// SERVER.C ###
#include <stdio.h>
#include <conio.h>
#include <winsock.h>
#include <windows.h>
WSADATA data;
SOCKET winsock;
SOCKADDR_IN sock;
char buffer[1024];
char buffer2[1024];
int bytes;
int main()
{
if(WSAStartup(MAKEWORD(1,1),&data) == SOCKET_ERROR){
printf("Erro ao inicializar o winsock");
return 0;
}
if((winsock = socket(AF_INET,SOCK_STREAM, 0)) == SOCKET_ERROR){
printf("Erro ao criar socket!!!");
return 0;
}
sock.sin_family = AF_INET;
sock.sin_port = htons(8080);
if(bind(winsock,(SOCKADDR*)&sock,sizeof(sock)) == SOCKET_ERROR){
printf("Erro ao abrir a porta no sistema (Erro em bind)!!!");
return 0;
}
listen(winsock, 1);
printf("Aguardando conexao!!!\n\n"); //
while((winsock = accept(winsock, 0 ,0)) == SOCKET_ERROR) // Não sai desse while ... Por algum motivo o cliente acima não se conecta !!!
{
Sleep(1);
}
// Não consigo chegar nessa parte pois estou travado na linha de cima ...
printf("Cliente conectado!!!\n");
while(1){
Sleep(1);
memset(buffer2, 0, 1024);
bytes = recv(winsock, buffer2, 1024, 0);
if(bytes == -1){
printf("Conexão perdida!!!\n");
closesocket(winsock);
WSACleanup();
getch();
return 0;
}
printf(buffer2);
printf("To: ");
gets(buffer);
printf("\n");
strcat(buffer,"\r\n");
send(winsock, buffer, strlen(buffer), 0);
}
closesocket(winsock);
WSACleanup();
return 0;
}
Por favor se alguem puder ajudar ficarei muito feliz =P ...
Discussão (1)
Carregando comentários...