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
') # 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
\r
"
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()
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Python pymysql 모듈 설치 및 조작 프로세스 분석pymsql은 Python에서 MySQL을 조작하는 모듈로 그 사용 방법은 MySQLdb와 거의 같다.하지만 현재pymysql는python3을 지원합니다.x와 후자는 지원하지 않습니다.x 버전. 본문 환경python...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.