Socket编程学习-基础操作
socket的基本操作
可参考,https://blog.csdn.net/sinat_36645384/article/details/79128137
核心问题1-UDP与TCP的区别
1、TCP是基于连接的基础上,而UDP是不需要的。这就导致了,TCP一般用recv获取数据,而UDP用recvfrom获取数据和地址。因为TCP是基于连接的基础上,所以获取地址就是多此一举了。
创建socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as msg:
print('Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1])
sys.exit()
注意,这里的socket.SOCK_STREAM指的是TCP。UDP用SOCK_DGRAM
连接指定ip
import socket
import sys
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as msg:
print('Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1])
sys.exit();
print('Socket Created')
host = 'www.oschina.net'
port = 80
try:
remote_ip = socket.gethostbyname( host )
except socket.gaierror:
print('Hostname could not be resolved. Exiting')
sys.exit()
print('Ip address of ' + host + ' is ' + remote_ip)
s.connect((remote_ip , port))
print('Socket Connected to ' + host + ' on ip ' + remote_ip)
Socket Created Ip address of www.oschina.net is 180.97.125.228 Socket Connected to www.oschina.net on ip 180.97.125.228
发送数据
message = "GET / HTTP/1.1\r\n\r\n"
try :
s.sendall(message)
except socket.error:
print('Send failed')
sys.exit()
print('Message send successfully')
报错:
s.sendall(message)
TypeError: a bytes-like object is required, not ‘str’
socket.socket def sendall(self, data: bytes, flags: int = …) -> None < Python 3.7 (pythonProject) (2) >
于是:
message = "GET / HTTP/1.1\r\n\r\n".encode()
接受数据
reply = s.recv(4096)
print reply
Socket Created Ip address of www.oschina.net is 180.97.125.228 Socket Connected to www.oschina.net on ip 180.97.125.228 Message send successfully b’HTTP/1.1 400 Bad Request\r\nServer: stgw/1.3.12_1.13.5\r\nDate: Sun, 23 Jan 2022 13:31:23 GMT\r\nContent-Type: text/html\r\nContent-Length: 179\r\nConnection: close\r\n\r\n\r\n 400 Bad Request\r\n\r\n
400 Bad Request
\r\n
stgw/1.3.12_1.13.5
\r\n\r\n\r\n’
因为 reply: bytes = s.recv(4096)
于是:
reply = s.recv(4096).decode()
Socket Created Ip address of www.oschina.net is 180.97.125.228 Socket Connected to www.oschina.net on ip 180.97.125.228 Message send successfully HTTP/1.1 400 Bad Request Server: stgw/1.3.12_1.13.5 Date: Sun, 23 Jan 2022 13:32:35 GMT Content-Type: text/html Content-Length: 179 Connection: close
400 Bad Request
400 Bad Request
stgw/1.3.12_1.13.5
关闭socket
s.close()
|