python_socket
2023-01-31 01:01:30
python
python Socket编程详细介绍(方法参数)
Http://blog.csdn.net/rebelqsp/article/details/22109925
服务端
# coding=utf-8
import socket
import sys
from thread import *
HOST = '' # Symbolic name meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
# 创建对象
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
# 绑定IP端口,真正创建socket
# Bind socket to local host and port
try:
s.bind((HOST, PORT))
# 如果创建 socket 函数失败,会抛出一个 socket.error 的异常,需要捕获
except socket.error, msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
# 监听
# Start listening on socket
s.listen(10)
print 'Socket now listening'
# 接受数据的方法
# Function for handling connections. This will be used to create threads
def clientthread(conn):
# Sending message to connected client
conn.send('Welcome to the server. Type something and hit enter\n') # send only takes string
# infinite loop so that function do not terminate and thread do not end.
while True:
# Receiving from client
data = conn.recv(1024)
reply = 'OK...' + data
if not data:
break
conn.sendall(reply)
# came out of loop
conn.close()
# 为每一个连接创建一个线程执行以上接受数据的方法
# now keep talking with the client
while 1:
# wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
# 用普通tread一样,自己给方法传参就是了
# start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
start_new_thread(clientthread, (conn,))
s.close()
客服端(这是http客服端 改改就能和上面的一起用)
import socket # for sockets
import sys # for exit
try:
# create an AF_INET, STREAM socket (tcp)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1]
sys.exit();
print 'Socket Created'
host = 'www.baidu.com'
port = 8080
try:
# 此方法可以通过域名获取IP
remote_ip = socket.gethostbyname(host)
except socket.gaierror:
# could not resolve
print 'Hostname could not be resolved. Exiting'
sys.exit()
print 'Ip address of ' + host + ' is ' + remote_ip
# Connect to remote server/与远端ip 端口 连接
s.connect((remote_ip, port))
print 'Socket Connected to ' + host + ' on ip ' + remote_ip
# Send some data to remote server/一串http的命令
message = "GET / HTTP/1.1\r\n\r\n"
try:
# Set the whole string//发送字符串
s.sendall(message)
except socket.error:
# Send failed
print 'Send failed'
sys.exit()
print 'Message send successfully'
# Now receive data//接受数据
reply = s.recv(4096)
print reply
# 聊天室类的 在连接后来个while 1 循环接受发送即可
s.close()
相关文章