Skip to content

Commit fc35aa6

Browse files
committed
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.
1 parent ff3bdea commit fc35aa6

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

unix/socket.c

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,42 @@ static mp_obj_t socket_accept(mp_obj_t self_in) {
127127
}
128128
static MP_DEFINE_CONST_FUN_OBJ_1(socket_accept_obj, socket_accept);
129129

130+
static mp_obj_t socket_recv(uint n_args, const mp_obj_t *args) {
131+
mp_obj_socket_t *self = args[0];
132+
int sz = MP_OBJ_SMALL_INT_VALUE(args[1]);
133+
int flags = 0;
134+
135+
if (n_args > 2) {
136+
flags = MP_OBJ_SMALL_INT_VALUE(args[2]);
137+
}
138+
139+
char *buf = m_new(char, sz + 1);
140+
int out_sz = recv(self->fd, buf, sz, flags);
141+
RAISE_ERRNO(out_sz, errno);
142+
143+
buf = m_realloc(buf, sz + 1, out_sz + 1);
144+
buf[out_sz] = 0;
145+
return MP_OBJ_NEW_QSTR(qstr_from_str_take(buf, out_sz + 1));
146+
}
147+
static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_recv_obj, 2, 3, socket_recv);
148+
149+
static mp_obj_t socket_send(uint n_args, const mp_obj_t *args) {
150+
mp_obj_socket_t *self = args[0];
151+
int flags = 0;
152+
153+
if (n_args > 2) {
154+
flags = MP_OBJ_SMALL_INT_VALUE(args[2]);
155+
}
156+
157+
const char *buf = qstr_str(mp_obj_str_get(args[1]));
158+
int sz = strlen(buf);
159+
int out_sz = send(self->fd, buf, sz, flags);
160+
RAISE_ERRNO(out_sz, errno);
161+
162+
return MP_OBJ_NEW_SMALL_INT(out_sz);
163+
}
164+
static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_send_obj, 2, 3, socket_send);
165+
130166
static mp_obj_t socket_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) {
131167
int family = AF_INET;
132168
int type = SOCK_STREAM;
@@ -159,6 +195,8 @@ static const mp_method_t rawsocket_type_methods[] = {
159195
{ "bind", &socket_bind_obj },
160196
{ "listen", &socket_listen_obj },
161197
{ "accept", &socket_accept_obj },
198+
{ "recv", &socket_recv_obj },
199+
{ "send", &socket_send_obj },
162200
{ "close", &socket_close_obj },
163201
#if MICROPY_SOCKET_EXTRA
164202
{ "recv", &mp_stream_read_obj },

0 commit comments

Comments
 (0)