Răsfoiți Sursa

update socket module for port/linux

Lyon 2 ani în urmă
părinte
comite
4abc50f8ef

+ 31 - 25
examples/socket/socket_GET.py

@@ -1,31 +1,37 @@
 import socket
 
-# 创建一个socket对象
-s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+def test_socket_GET():
+    # 创建一个socket对象
+    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 
-# 获取服务器的IP地址
-server_ip = socket.gethostbyname('baidu.com')
-server_port = 80
+    # 获取服务器的IP地址
+    # server_ip = socket.gethostbyname('baidu.com')
+    server_port = 80
 
-# 连接到服务器
-s.connect((server_ip, server_port))
-# 创建HTTP GET请求
-request = 'GET / HTTP/1.1\r\nHost: baidu.com\r\n\r\n'
-# print('request:', request)
-s.send(request.encode())
+    # 连接到服务器
+    s.connect(('pikapython.com', server_port))
+    # 创建HTTP GET请求
+    request = 'GET / HTTP/1.1\r\nHost: pikascript.com\r\n\r\n'
+    # print('request:', request)
+    s.send(request.encode())
 
-# 接收服务器的响应
-response = ''
-while True:
-    try:
-        recv = s.recv(1024)
-    except:
-        break
-    if not recv:
-        break
-    response += recv.decode()
+    # 接收服务器的响应
+    response = ''
+    while True:
+        try:
+            recv = s.recv(1024)
+        except:
+            break
+        if not recv:
+            break
+        response += recv.decode()
+    s.close()
+    return response
 
-s.close()
-
-assert 'HTTP/1.1 200 OK' in response
-print('PASS')
+for i in range(10):
+    response = test_socket_GET()
+    res = 'HTTP/1.1' in response
+    if res == True:
+        break
+    print('test_socket_GET() failed, retrying...')
+    print('response', response)

+ 9 - 13
package/socket/PikaPlatform_socket.c

@@ -10,7 +10,7 @@
 static int pika_platform_winsock_initialized = 0;
 
 int pika_platform_init_winsock() {
-    if(0 == pika_platform_winsock_initialized) {
+    if (0 == pika_platform_winsock_initialized) {
         WSADATA wsaData;
         int res = WSAStartup(MAKEWORD(2, 2), &wsaData);
         if (res != 0) {
@@ -18,21 +18,17 @@ int pika_platform_init_winsock() {
             return 1;
         }
         pika_platform_winsock_initialized = 1;
-    }
-    else if(0 < pika_platform_winsock_initialized)
-    {
+    } else if (0 < pika_platform_winsock_initialized) {
         pika_platform_winsock_initialized++;
     }
     return 0;
 }
 
 int pika_platform_cleanup_winsock() {
-    if(1 == pika_platform_winsock_initialized) {
+    if (1 == pika_platform_winsock_initialized) {
         WSACleanup();
         pika_platform_winsock_initialized = 0;
-    }
-    else if(1 < pika_platform_winsock_initialized)
-    {
+    } else if (1 < pika_platform_winsock_initialized) {
         pika_platform_winsock_initialized--;
     }
     return 0;
@@ -180,12 +176,12 @@ PIKA_WEAK int pika_platform_fcntl(int fd, int cmd, long arg) {
     return fcntl(fd, cmd, arg);
 #elif defined(_WIN32)
     if (cmd == F_GETFL) {
-       u_long mode = 0;
-       ioctlsocket(fd, FIONBIO, &mode);
-       return (mode ? O_NONBLOCK : 0);
+        u_long mode = 0;
+        ioctlsocket(fd, FIONBIO, &mode);
+        return (mode ? O_NONBLOCK : 0);
     } else if (cmd == F_SETFL) {
-       u_long mode = (arg & O_NONBLOCK) ? 1 : 0;
-       return ioctlsocket(fd, FIONBIO, &mode);
+        u_long mode = (arg & O_NONBLOCK) ? 1 : 0;
+        return ioctlsocket(fd, FIONBIO, &mode);
     }
     return -1;
 #else

+ 3 - 3
package/socket/PikaPlatform_socket.h

@@ -16,10 +16,10 @@
 #include <ws2tcpip.h>
 #include <iphlpapi.h>
 #include <io.h>
-#define O_NONBLOCK      0x0004  /* non blocking I/O, from BSD */
+#define O_NONBLOCK 0x0004 /* non blocking I/O, from BSD */
 
-#define F_GETFL  3
-#define F_SETFL  4
+#define F_GETFL 3
+#define F_SETFL 4
 
 int pika_platform_init_winsock();
 int pika_platform_cleanup_winsock();

+ 5 - 4
package/socket/_socket.c

@@ -177,9 +177,9 @@ char* _socket__gethostname(PikaObj* self) {
     return obj_cacheStr(self, hostname);
 }
 
-char* _socket__gethostbyname(PikaObj *self, char* host){
-    struct hostent *host_entry;
-    char *ip = NULL;
+char* _socket__gethostbyname(PikaObj* self, char* host) {
+    struct hostent* host_entry;
+    char* ip = NULL;
 #ifdef _WIN32
     pika_platform_init_winsock();
 #endif
@@ -189,7 +189,8 @@ char* _socket__gethostbyname(PikaObj *self, char* host){
         __platform_printf("gethostbyname error\n");
         return NULL;
     }
-    ip = pika_platform_inet_ntoa(*((struct in_addr *)host_entry->h_addr_list[0]));
+    ip =
+        pika_platform_inet_ntoa(*((struct in_addr*)host_entry->h_addr_list[0]));
 #ifdef _WIN32
     pika_platform_cleanup_winsock();
 #endif

+ 61 - 18
port/linux/package/pikascript/pikascript-lib/socket/PikaPlatform_socket.c

@@ -1,11 +1,42 @@
-#include "PikaPlatform_socket.h"
+#include "PikaPlatform_socket.h"
 /*
     The functinos start with PIKA_WEAK are weak functions,
     you need to override them in your platform.
 */
 
+#ifdef _WIN32
+#pragma comment(lib, "ws2_32.lib")
+
+static int pika_platform_winsock_initialized = 0;
+
+int pika_platform_init_winsock() {
+    if (0 == pika_platform_winsock_initialized) {
+        WSADATA wsaData;
+        int res = WSAStartup(MAKEWORD(2, 2), &wsaData);
+        if (res != 0) {
+            __platform_printf("WSAStartup failed with error: %d\n", res);
+            return 1;
+        }
+        pika_platform_winsock_initialized = 1;
+    } else if (0 < pika_platform_winsock_initialized) {
+        pika_platform_winsock_initialized++;
+    }
+    return 0;
+}
+
+int pika_platform_cleanup_winsock() {
+    if (1 == pika_platform_winsock_initialized) {
+        WSACleanup();
+        pika_platform_winsock_initialized = 0;
+    } else if (1 < pika_platform_winsock_initialized) {
+        pika_platform_winsock_initialized--;
+    }
+    return 0;
+}
+#endif
+
 PIKA_WEAK int pika_platform_socket(int __domain, int __type, int __protocol) {
-#if defined(__linux__) || PIKA_LWIP_ENABLE
+#if defined(__linux__) || defined(_WIN32) || PIKA_LWIP_ENABLE
     return socket(__domain, __type, __protocol);
 #else
     WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
@@ -15,7 +46,7 @@ PIKA_WEAK int pika_platform_socket(int __domain, int __type, int __protocol) {
 PIKA_WEAK int pika_platform_bind(int __fd,
                                  const struct sockaddr* __addr,
                                  socklen_t __addr_len) {
-#if defined(__linux__) || PIKA_LWIP_ENABLE
+#if defined(__linux__) || defined(_WIN32) || PIKA_LWIP_ENABLE
     return bind(__fd, __addr, __addr_len);
 #else
     WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
@@ -23,7 +54,7 @@ PIKA_WEAK int pika_platform_bind(int __fd,
 }
 
 PIKA_WEAK int pika_platform_listen(int __fd, int __n) {
-#if defined(__linux__) || PIKA_LWIP_ENABLE
+#if defined(__linux__) || defined(_WIN32) || PIKA_LWIP_ENABLE
     return listen(__fd, __n);
 #else
     WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
@@ -33,7 +64,7 @@ PIKA_WEAK int pika_platform_listen(int __fd, int __n) {
 PIKA_WEAK int pika_platform_accept(int __fd,
                                    struct sockaddr* __addr,
                                    socklen_t* __addr_len) {
-#if defined(__linux__) || PIKA_LWIP_ENABLE
+#if defined(__linux__) || defined(_WIN32) || PIKA_LWIP_ENABLE
     return accept(__fd, __addr, __addr_len);
 #else
     WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
@@ -43,7 +74,7 @@ PIKA_WEAK int pika_platform_accept(int __fd,
 PIKA_WEAK int pika_platform_connect(int __fd,
                                     const struct sockaddr* __addr,
                                     socklen_t __addr_len) {
-#if defined(__linux__) || PIKA_LWIP_ENABLE
+#if defined(__linux__) || defined(_WIN32) || PIKA_LWIP_ENABLE
     return connect(__fd, __addr, __addr_len);
 #else
     WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
@@ -51,7 +82,7 @@ PIKA_WEAK int pika_platform_connect(int __fd,
 }
 
 PIKA_WEAK int pika_platform_htons(int __hostshort) {
-#if defined(__linux__) || PIKA_LWIP_ENABLE
+#if defined(__linux__) || defined(_WIN32) || PIKA_LWIP_ENABLE
     return htons(__hostshort);
 #else
     WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
@@ -60,7 +91,7 @@ PIKA_WEAK int pika_platform_htons(int __hostshort) {
 
 /* gethostbyname */
 PIKA_WEAK struct hostent* pika_platform_gethostbyname(const char* __name) {
-#if defined(__linux__) || PIKA_LWIP_ENABLE
+#if defined(__linux__) || defined(_WIN32) || PIKA_LWIP_ENABLE
     return gethostbyname(__name);
 #else
     WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
@@ -68,9 +99,9 @@ PIKA_WEAK struct hostent* pika_platform_gethostbyname(const char* __name) {
 }
 
 /* inet_ntoa */
-PIKA_WEAK char* pika_platform_inet_ntoa(struct in_addr __in) {
-#if defined(__linux__) || PIKA_LWIP_ENABLE
-    return inet_ntoa(__in);
+PIKA_WEAK char* pika_platform_inet_ntoa(struct in_addr in_addr_val) {
+#if defined(__linux__) || defined(_WIN32) || PIKA_LWIP_ENABLE
+    return inet_ntoa(in_addr_val);
 #else
     WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
 #endif
@@ -80,7 +111,7 @@ PIKA_WEAK int pika_platform_send(int __fd,
                                  const void* __buf,
                                  size_t __n,
                                  int __flags) {
-#if defined(__linux__) || PIKA_LWIP_ENABLE
+#if defined(__linux__) || defined(_WIN32) || PIKA_LWIP_ENABLE
     return send(__fd, __buf, __n, __flags);
 #else
     WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
@@ -91,7 +122,7 @@ PIKA_WEAK int pika_platform_recv(int __fd,
                                  void* __buf,
                                  size_t __n,
                                  int __flags) {
-#if defined(__linux__) || PIKA_LWIP_ENABLE
+#if defined(__linux__) || defined(_WIN32) || PIKA_LWIP_ENABLE
     return recv(__fd, __buf, __n, __flags);
 #else
     WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
@@ -101,7 +132,7 @@ PIKA_WEAK int pika_platform_recv(int __fd,
 
 /* gethostname */
 PIKA_WEAK int pika_platform_gethostname(char* __name, size_t __len) {
-#if defined(__linux__)
+#if defined(__linux__) || defined(_WIN32)
     return gethostname(__name, __len);
 #else
     WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
@@ -113,7 +144,7 @@ PIKA_WEAK int pika_platform_getaddrinfo(const char* __name,
                                         const char* __service,
                                         const struct addrinfo* __req,
                                         struct addrinfo** __pai) {
-#if defined(__linux__) || PIKA_LWIP_ENABLE
+#if defined(__linux__) || defined(_WIN32) || PIKA_LWIP_ENABLE
     return getaddrinfo(__name, __service, __req, __pai);
 #else
     WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
@@ -121,7 +152,7 @@ PIKA_WEAK int pika_platform_getaddrinfo(const char* __name,
 }
 
 PIKA_WEAK void pika_platform_freeaddrinfo(struct addrinfo* __ai) {
-#if defined(__linux__) || PIKA_LWIP_ENABLE
+#if defined(__linux__) || defined(_WIN32) || PIKA_LWIP_ENABLE
     freeaddrinfo(__ai);
 #else
     WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
@@ -133,7 +164,7 @@ PIKA_WEAK int pika_platform_setsockopt(int __fd,
                                        int __optname,
                                        const void* __optval,
                                        socklen_t __optlen) {
-#if defined(__linux__) || PIKA_LWIP_ENABLE
+#if defined(__linux__) || defined(_WIN32) || PIKA_LWIP_ENABLE
     return setsockopt(__fd, __level, __optname, __optval, __optlen);
 #else
     WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
@@ -143,6 +174,16 @@ PIKA_WEAK int pika_platform_setsockopt(int __fd,
 PIKA_WEAK int pika_platform_fcntl(int fd, int cmd, long arg) {
 #if defined(__linux__) || PIKA_LWIP_ENABLE
     return fcntl(fd, cmd, arg);
+#elif defined(_WIN32)
+    if (cmd == F_GETFL) {
+        u_long mode = 0;
+        ioctlsocket(fd, FIONBIO, &mode);
+        return (mode ? O_NONBLOCK : 0);
+    } else if (cmd == F_SETFL) {
+        u_long mode = (arg & O_NONBLOCK) ? 1 : 0;
+        return ioctlsocket(fd, FIONBIO, &mode);
+    }
+    return -1;
 #else
     WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
 #endif
@@ -152,6 +193,8 @@ PIKA_WEAK int pika_platform_fcntl(int fd, int cmd, long arg) {
 PIKA_WEAK int pika_platform_close(int __fd) {
 #if defined(__linux__) || PIKA_LWIP_ENABLE
     return close(__fd);
+#elif defined(_WIN32)
+    return closesocket(__fd);
 #elif PIKA_FREERTOS_ENABLE
     return closesocket(__fd);
 #else
@@ -160,7 +203,7 @@ PIKA_WEAK int pika_platform_close(int __fd) {
 }
 
 PIKA_WEAK int pika_platform_write(int __fd, const void* __buf, size_t __nbyte) {
-#if defined(__linux__) || PIKA_LWIP_ENABLE
+#if defined(__linux__) || defined(_WIN32) || PIKA_LWIP_ENABLE
     return write(__fd, __buf, __nbyte);
 #else
     WEAK_FUNCTION_NEED_OVERRIDE_ERROR();

+ 19 - 2
port/linux/package/pikascript/pikascript-lib/socket/PikaPlatform_socket.h

@@ -1,4 +1,4 @@
-#include "PikaObj.h"
+#include "PikaObj.h"
 #ifdef __linux__
 #include <arpa/inet.h>
 #include <errno.h>
@@ -6,6 +6,23 @@
 #include <netdb.h>
 #include <sys/socket.h>
 #include <unistd.h>
+#elif _WIN32
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN
+#endif
+#include <stdio.h>
+#include <windows.h>
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#include <iphlpapi.h>
+#include <io.h>
+#define O_NONBLOCK 0x0004 /* non blocking I/O, from BSD */
+
+#define F_GETFL 3
+#define F_SETFL 4
+
+int pika_platform_init_winsock();
+int pika_platform_cleanup_winsock();
 #elif PIKA_LWIP_ENABLE
 #include <lwip/sockets.h>
 #include "lwip/api.h"
@@ -46,7 +63,7 @@ int pika_platform_setsockopt(int __fd,
                              const void* __optval,
                              socklen_t __optlen);
 int pika_platform_htons(int __hostshort);
-char* pika_platform_inet_ntoa(struct in_addr __in);
+char* pika_platform_inet_ntoa(struct in_addr in_addr_val);
 struct hostent* pika_platform_gethostbyname(const char* __name);
 
 /* os file API */

+ 20 - 2
port/linux/package/pikascript/pikascript-lib/socket/_socket.c

@@ -1,4 +1,4 @@
-#include "PikaPlatform_socket.h"
+#include "PikaPlatform_socket.h"
 #include "_socket_socket.h"
 
 #if !PIKASCRIPT_VERSION_REQUIRE_MINIMUN(1, 12, 0)
@@ -10,6 +10,9 @@ void _socket_socket__init(PikaObj* self) {
     int type = obj_getInt(self, "type");
     int protocol = obj_getInt(self, "protocol");
     int sockfd = 0;
+#ifdef _WIN32
+    pika_platform_init_winsock();
+#endif
     sockfd = __platform_socket(family, type, protocol);
     if (sockfd < 0) {
         obj_setErrorCode(self, PIKA_RES_ERR_RUNTIME_ERROR);
@@ -23,6 +26,9 @@ void _socket_socket__init(PikaObj* self) {
 void _socket_socket__close(PikaObj* self) {
     int sockfd = obj_getInt(self, "sockfd");
     __platform_close(sockfd);
+#ifdef _WIN32
+    pika_platform_cleanup_winsock();
+#endif
 }
 
 void _socket_socket__send(PikaObj* self, Arg* data) {
@@ -161,13 +167,22 @@ void _socket_socket__bind(PikaObj* self, char* host, int port) {
 char* _socket__gethostname(PikaObj* self) {
     char hostname_buff[128] = {0};
     char* hostname = (char*)hostname_buff;
-    __platform_gethostname(hostname_buff, 128);
+#ifdef _WIN32
+    pika_platform_init_winsock();
+#endif
+    pika_platform_gethostname(hostname_buff, 128);
+#ifdef _WIN32
+    pika_platform_cleanup_winsock();
+#endif
     return obj_cacheStr(self, hostname);
 }
 
 char* _socket__gethostbyname(PikaObj* self, char* host) {
     struct hostent* host_entry;
     char* ip = NULL;
+#ifdef _WIN32
+    pika_platform_init_winsock();
+#endif
     host_entry = pika_platform_gethostbyname(host);
     if (host_entry == NULL) {
         obj_setErrorCode(self, PIKA_RES_ERR_RUNTIME_ERROR);
@@ -176,6 +191,9 @@ char* _socket__gethostbyname(PikaObj* self, char* host) {
     }
     ip =
         pika_platform_inet_ntoa(*((struct in_addr*)host_entry->h_addr_list[0]));
+#ifdef _WIN32
+    pika_platform_cleanup_winsock();
+#endif
     return obj_cacheStr(self, ip);
 }
 

+ 17 - 0
port/linux/package/pikascript/pikascript-lib/socket/_socket.pyi

@@ -0,0 +1,17 @@
+from PikaObj import *
+
+
+class socket:
+    def _bind(host: str, port: int): ...
+    def _listen(num: int): ...
+    def _accept(): ...
+    def _send(data: any): ...
+    def _close(): ...
+    def _connect(host: str, port: int): ...
+    def _recv(num: int) -> bytes: ...
+    def _init(): ...
+    def _setblocking(sta: int): ...
+
+
+def _gethostname() -> str: ...
+def _gethostbyname(host: str) -> str: ...

+ 66 - 0
port/linux/package/pikascript/pikascript-lib/socket/socket.py

@@ -0,0 +1,66 @@
+import _socket
+
+AF_INET = 2
+SOCK_STREAM = 1
+
+
+
+class socket(_socket.socket):
+    family = AF_INET
+    type = SOCK_STREAM
+    sockfd = 0
+    client_sockfd = 0
+    client_addr = ''
+    protocol = 0
+
+    def __init__(self, *vars):
+        if len(vars) > 0:
+            self.family = vars[0]
+        if len(vars) > 1:
+            self.type = vars[1]
+        if len(vars) > 2:
+            self.proto = vars[2]
+        self._init()
+
+    def bind(self, host_port):
+        host = host_port[0]
+        port = host_port[1]
+        return self._bind(host, port)
+
+    def listen(self, num):
+        return self._listen(num)
+
+    def accept(self):
+        self._accept()
+        client = socket()
+        client.sockfd = self.client_sockfd
+        return (client, self.client_addr)
+
+    def send(self, data):
+        return self._send(data)
+
+    def close(self):
+        self._close()
+
+    def connect(self, host_port):
+        host = host_port[0]
+        port = host_port[1]
+        if type(host) != str:
+            print('Error: host must be a string')
+            raise
+        if type(port) != int:
+            print('Error: port must be an integer')
+            raise
+        return self._connect(host, port)
+
+    def recv(self, num):
+        return self._recv(num)
+
+    def setblocking(self, sta): 
+        return self._setblocking(sta)
+
+def gethostname():
+    return _socket._gethostname()
+
+def gethostbyname(host):
+    return _socket._gethostbyname(host)

+ 3 - 3
port/linux/push-core.sh

@@ -3,6 +3,9 @@ FLAG_OK="\033[32m[ OK ]\033[0m"
 FLAG_INFO="\033[32m[Info]\033[0m"
 FLAG_NOTE="\033[35m[Note]\033[0m"
 
+sh version.sh
+python3 format.py
+
 if [ -d "../../../pikalab" ]; then
     sh lab-push.sh
 fi
@@ -17,9 +20,6 @@ sh std_push.sh PikaDebug
 sh std_push.sh PikaStdTask
 sh std_push.sh builtins
 
-sh version.sh
-python3 format.py
-
 echo "$FLAG_OK Push \033[32mpikascript-core\033[0m to ../../src successfully!"
 echo "$FLAG_OK Push \033[32mPikaSdLib\033[0m to ../../package/PikaStdLib successfully!"
 echo "$FLAG_NOTE Now, you can run 'git commit -a' to commit changes."

+ 1 - 1
src/PikaVersion.h

@@ -2,4 +2,4 @@
 #define PIKA_VERSION_MINOR 12
 #define PIKA_VERSION_MICRO 4
 
-#define PIKA_EDIT_TIME "2023/07/28 10:40:54"
+#define PIKA_EDIT_TIME "2023/07/30 21:11:36"

+ 1 - 0
src/pika_adapter_old_api.h

@@ -46,6 +46,7 @@ extern "C" {
 #define __platform_getTick pika_platform_get_tick
 #define pika_platform_getTick pika_platform_get_tick
 #define __platform_sleep_ms pika_platform_sleep_ms
+#define __platform_sleep_s pika_platform_sleep_s
 
 #define __pks_hook_instruct pika_hook_instruct
 #define __pks_hook_arg_cache_filter pika_hook_arg_cache_filter