Commit 55152cf7 authored by Xavier Thompson's avatar Xavier Thompson

Add server.pyx and client.pyx demo

parent fbe547e6
from stdlib.string cimport Str
from stdlib.socket cimport getaddrinfo, socket, AF_UNSPEC, SOCK_STREAM, AI_PASSIVE, MSG_WAITALL, SHUT_WR, SHUT_RD
from libc.stdio cimport puts, printf
def main():
cdef const char * arg
while True:
b = input("Message to send:\n").encode()
arg = b
with nogil:
a = getaddrinfo(NULL, Str("3490"), AF_UNSPEC, SOCK_STREAM, 0, AI_PASSIVE)[0]
s = socket(a.family, a.socktype, a.protocol)
puts('open: ok')
s.connect(a.sockaddr)
puts('connect: ok')
msg = Str(arg)
s.sendall(msg)
puts('send: ok')
s.shutdown(SHUT_WR)
r = Str('')
while True:
rcv = s.recv(100)
if rcv.__len__() > 0:
printf('recv: %s\n', Str.to_c_str(rcv))
r = r + rcv
else:
puts('connection closed by server')
break
printf('got: %s\n', Str.to_c_str(r))
s.close()
puts('close: ok')
main()
from stdlib.string cimport Str
from stdlib.socket cimport getaddrinfo, socket, AF_UNSPEC, SOCK_STREAM, AI_PASSIVE, SHUT_RD, SHUT_WR
from libc.stdio cimport puts, printf
def main():
with nogil:
a = getaddrinfo(NULL, Str("3490"), AF_UNSPEC, SOCK_STREAM, 0, AI_PASSIVE)[0]
s = socket(a.family, a.socktype, a.protocol)
puts('open: ok')
s.bind(a.sockaddr)
puts('bind: ok')
s.listen(5)
puts('listen: ok')
while True:
s1 = s.accept()
puts('accept: ok')
r = Str('')
while True:
rcv = s1.recv(100)
if rcv.__len__() > 0:
printf('recv: %s\n', Str.to_c_str(rcv))
r = r + rcv
else:
puts('connection closed by client')
break
s1.shutdown(SHUT_RD)
s1.sendall(r)
puts('send: ok')
s1.shutdown(SHUT_WR)
s1.close()
puts('close 1: ok')
s.close()
puts('close 0: ok')
main()
...@@ -105,6 +105,13 @@ cdef extern from "<netinet/in.h>" nogil: ...@@ -105,6 +105,13 @@ cdef extern from "<netinet/in.h>" nogil:
enum: INET6_ADDRSTRLEN enum: INET6_ADDRSTRLEN
unsigned long htonl(unsigned long hostlong)
unsigned short htons(unsigned short hostshort)
unsigned long ntohl(unsigned long netlong)
unsigned short ntohs(unsigned short netshort)
cdef extern from "<arpa/inet.h>" nogil: cdef extern from "<arpa/inet.h>" nogil:
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) const char *inet_ntop(int af, const void *src, char *dst, socklen_t size)
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment