LwIP NETCONN: Simultaneous Server and Client Code Example
This code provides a basic example of creating a server and a client using LwIP's NETCONN API in a single program:
#include "lwip/opt.h"
#include "lwip/api.h"
#include "lwip/sys.h"
#include "lwip/sockets.h"
#include "lwip/inet.h"
#define SERVER_PORT 1234
#define CLIENT_PORT 5678
static void server_thread(void *arg)
{
struct netconn *conn, *newconn;
err_t err;
char buffer[1024];
// Create a new connection
conn = netconn_new(NETCONN_TCP);
if (conn != NULL) {
// Bind to the specified port
err = netconn_bind(conn, NULL, SERVER_PORT);
if (err == ERR_OK) {
// Listen for incoming connections
err = netconn_listen(conn);
if (err == ERR_OK) {
while (1) {
// Wait for a new connection
err = netconn_accept(conn, &newconn);
if (err == ERR_OK) {
// Receive data from the client
err = netconn_recv(newconn, &buffer, sizeof(buffer), NETCONN_COPY);
if (err == ERR_OK) {
// Process the data
printf('Received data: %s\n', buffer);
// Send a response
err = netconn_write(newconn, 'Hello from server!', sizeof('Hello from server!'), NETCONN_COPY);
}
// Close the connection
netconn_close(newconn);
netconn_delete(newconn);
}
}
}
}
// Close the connection
netconn_close(conn);
netconn_delete(conn);
}
}
static void client_thread(void *arg)
{
struct netconn *conn;
err_t err;
char buffer[1024];
// Create a new connection
conn = netconn_new(NETCONN_TCP);
if (conn != NULL) {
// Connect to the server
err = netconn_connect(conn, IP_ADDR_ANY, SERVER_PORT);
if (err == ERR_OK) {
// Send data to the server
err = netconn_write(conn, 'Hello from client!', sizeof('Hello from client!'), NETCONN_COPY);
if (err == ERR_OK) {
// Receive the response from the server
err = netconn_recv(conn, &buffer, sizeof(buffer), NETCONN_COPY);
if (err == ERR_OK) {
// Process the response
printf('Received data: %s\n', buffer);
}
}
}
// Close the connection
netconn_close(conn);
netconn_delete(conn);
}
}
int main()
{
sys_thread_new("server", server_thread, NULL, 1024, 0);
sys_thread_new("client", client_thread, NULL, 1024, 0);
while (1) {
// Do nothing
}
return 0;
}
The code creates two threads: one for the server and one for the client. The server thread creates a new connection, binds to a specified port, and listens for incoming connections. Upon a connection request, the server accepts the connection, reads data from the client, processes it, sends a response, and then closes the connection. The client thread creates a new connection, connects to the server, and sends data to the server. It then reads the server's response, processes it, and closes the connection. This example utilizes LwIP's NETCONN API for implementing server and client functionality.
AI 优化版
原文地址:https://www.cveoy.top/t/topic/kyZp 著作权归作者所有。请勿转载和采集!