我写了这个程序:
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int socket_desc;
struct sockaddr_in adress;
int addrlen;
int new_socket;
int bufsize = 1024;
char *you_sent = "You sent: ";
int main() {
char *buffer = malloc(bufsize);
socket_desc = socket(AF_INET, SOCK_STREAM, 0);
adress.sin_family = AF_INET;
adress.sin_addr.s_addr = INADDR_ANY;
adress.sin_port = htons(7000);
bind(socket_desc, (struct sockaddr *)&adress, sizeof(adress));
listen(socket_desc, 3);
addrlen = sizeof(struct sockaddr_in);
new_socket = accept(socket_desc, (struct sockaddr *)&adress, &addrlen);
while(recv(new_socket,buffer,bufsize,0))
{
printf("I recieved: %s", buffer);
send(new_socket, you_sent, strlen(you_sent), 0);
send(new_socket, buffer, strlen(buffer), 0);
memset(buffer, '\0', sizeof(buffer));
}
}
我可以通过 telnet 连接到服务器。并将内容写入应用程序并从应用程序接收数据。但是我无法理解如何使用另一个 c 程序连接到该程序并从该程序发送和接收数据。我试过这个:
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int socket_desc;
struct sockaddr_in adress;
int addrlen;
int new_socket;
char *message_to_send = "Hello world!";
int main() {
socket_desc = socket(AF_INET, SOCK_STREAM, 0);
adress.sin_family = AF_INET;
adress.sin_addr.s_addr = INADDR_ANY;
adress.sin_port = htons(7000);
bind(socket_desc, (struct sockaddr *)&adress, sizeof(adress));
listen(socket_desc, 3);
addrlen = sizeof(struct sockaddr_in);
new_socket = accept(socket_desc, (struct sockaddr *)&adress, &addrlen);
send(new_socket, message_to_send, strlen(message_to_send), 0);
}