From fc35aa682847e9123064eeaf5955c06275b95a0d Mon Sep 17 00:00:00 2001 From: Paul Sokolovsky Date: Mon, 20 Jan 2014 19:42:39 +0200 Subject: unix socket: Add send() and recv() methods. CPython _socket actually have only those and doesn't provide stream interface (higher-level CPython "socket" what adds this). +516 bytes x86. --- unix/socket.c | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) (limited to 'unix/socket.c') diff --git a/unix/socket.c b/unix/socket.c index 708cf7af52..7da6bb20d0 100644 --- a/unix/socket.c +++ b/unix/socket.c @@ -127,6 +127,42 @@ static mp_obj_t socket_accept(mp_obj_t self_in) { } static MP_DEFINE_CONST_FUN_OBJ_1(socket_accept_obj, socket_accept); +static mp_obj_t socket_recv(uint n_args, const mp_obj_t *args) { + mp_obj_socket_t *self = args[0]; + int sz = MP_OBJ_SMALL_INT_VALUE(args[1]); + int flags = 0; + + if (n_args > 2) { + flags = MP_OBJ_SMALL_INT_VALUE(args[2]); + } + + char *buf = m_new(char, sz + 1); + int out_sz = recv(self->fd, buf, sz, flags); + RAISE_ERRNO(out_sz, errno); + + buf = m_realloc(buf, sz + 1, out_sz + 1); + buf[out_sz] = 0; + return MP_OBJ_NEW_QSTR(qstr_from_str_take(buf, out_sz + 1)); +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_recv_obj, 2, 3, socket_recv); + +static mp_obj_t socket_send(uint n_args, const mp_obj_t *args) { + mp_obj_socket_t *self = args[0]; + int flags = 0; + + if (n_args > 2) { + flags = MP_OBJ_SMALL_INT_VALUE(args[2]); + } + + const char *buf = qstr_str(mp_obj_str_get(args[1])); + int sz = strlen(buf); + int out_sz = send(self->fd, buf, sz, flags); + RAISE_ERRNO(out_sz, errno); + + return MP_OBJ_NEW_SMALL_INT(out_sz); +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_send_obj, 2, 3, socket_send); + static mp_obj_t socket_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) { int family = AF_INET; int type = SOCK_STREAM; @@ -159,6 +195,8 @@ static const mp_method_t rawsocket_type_methods[] = { { "bind", &socket_bind_obj }, { "listen", &socket_listen_obj }, { "accept", &socket_accept_obj }, + { "recv", &socket_recv_obj }, + { "send", &socket_send_obj }, { "close", &socket_close_obj }, #if MICROPY_SOCKET_EXTRA { "recv", &mp_stream_read_obj }, -- cgit v1.2.3 From f0cfb8cb45cb1fc91c77fae98f5452b7f7865392 Mon Sep 17 00:00:00 2001 From: Paul Sokolovsky Date: Mon, 20 Jan 2014 20:10:37 +0200 Subject: Don't preimport socket module. --- unix/socket.c | 1 - 1 file changed, 1 deletion(-) (limited to 'unix/socket.c') diff --git a/unix/socket.c b/unix/socket.c index 7da6bb20d0..e48d8545f7 100644 --- a/unix/socket.c +++ b/unix/socket.c @@ -318,5 +318,4 @@ void rawsocket_init() { STORE_INT_CONST(m, SOCK_STREAM); STORE_INT_CONST(m, SOCK_DGRAM); STORE_INT_CONST(m, SOCK_RAW); - rt_store_name(qstr_from_str_static("rawsocket"), m); } -- cgit v1.2.3