在Linux系统中,Socket.5并不是一个标准的协议
sudo apt-get update
sudo apt-get install libevent-dev
sudo apt-get install libev-dev
服务器端(server.c):
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <event2/event.h>
#include <event2/http.h>
static void cb(evutil_socket_t fd, short events, void *arg) {
struct evhttp *http = (struct evhttp *)arg;
struct evhttp_request *req = evhttp_request_new(NULL, NULL);
if (!req) {
fprintf(stderr, "Could not allocate request\n");
return;
}
evhttp_add_header(req->output_headers, "Content-Type", "text/plain");
evhttp_add_header(req->output_headers, "Connection", "close");
evhttp_send_reply(req, HTTP_OK, "Hello, Socket.5!", NULL);
evhttp_free(req);
}
int main() {
struct event_base *base = event_base_new();
if (!base) {
fprintf(stderr, "Could not create event base\n");
return 1;
}
struct evhttp *http = evhttp_new(base);
if (!http) {
fprintf(stderr, "Could not create HTTP server\n");
return 1;
}
evhttp_set_gencb(http, cb, NULL);
evhttp_bind_socket(http, "0.0.0.0:8080", NULL);
event_base_dispatch(base);
evhttp_free(http);
event_base_free(base);
return 0;
}
客户端(client.c):
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <event2/event.h>
#include <event2/http.h>
static void cb(struct evhttp_request *req, void *arg) {
char *buf = malloc(1024);
if (!buf) {
fprintf(stderr, "Could not allocate buffer\n");
return;
}
ssize_t len = evhttp_read(req, buf, 1023);
if (len != -1) {
buf[len] = '\0';
printf("Received: %s\n", buf);
} else {
perror("evhttp_read");
}
free(buf);
evhttp_free(req);
}
int main() {
struct event_base *base = event_base_new();
if (!base) {
fprintf(stderr, "Could not create event base\n");
return 1;
}
struct evhttp *http = evhttp_new(base);
if (!http) {
fprintf(stderr, "Could not create HTTP client\n");
return 1;
}
struct evhttp_request *req = evhttp_request_new(HTTP_GET, "/");
if (!req) {
fprintf(stderr, "Could not allocate request\n");
return 1;
}
evhttp_add_header(req->output_headers, "Host", "localhost");
evhttp_set_cb(req, cb, NULL);
evhttp_send(req, http);
event_base_dispatch(base);
evhttp_free(http);
evhttp_free(req);
event_base_free(base);
return 0;
}
gcc server.c -o server -levent -levent_http
gcc client.c -o client -levent -levent_http
./server
./client
现在你已经成功创建了一个简单的Socket.5服务器和客户端。请注意,这个示例使用了libevent库,而不是原生的Socket.5库,因为Socket.5并不是一个标准的协议。