tcp
from socket import *
host = "127.0.0.1"
port = 12345
addr = (host, port)
server = socket (af_inet, sock_stream)
server.bind (addr)
server.listen (5)
print ("start listen...")
client, addr = server.accept ()
print ("accept a connection from %s" % str (addr))
data = client.recv (1024)
ifnot data:
print ("there is no data")
print ("exit the server process")
exit ()
print ("received a msg from client : %s" % str (data, encoding = "utf-8"))
client.send (bytes ("server received.", encoding = "utf8"))
client.close ()
exit ()
from socket import *
host = "127.0.0.1"
port = 12345
addr = (host, port)
client = socket (af_inet, sock_stream)
client.connect (addr)
client.send (bytes ("hehe", encoding = "utf8"))
data = client.recv (1024)
print ("receive data : %s" % str (data, encoding = "utf-8"))
print ("close socket")
client.close ()
exit ()
說明:
必須用from socket import *,不能用import socket
使用print ()函式時,可以用 print (「*** %s」 % m_str)格式化輸出字串,也可以用 print (「***」, m_str) 連線多個字串
程式中 addr 是乙個tuple,不能在 print 中這樣寫:print ("*** %s" % addr)
,會報錯的。可以這樣寫:print ("*** %s" % str (addr))
呼叫 send () 函式時,必須把要傳送的字串轉換成 bytes 格式才能傳送。注意在使用 bytes () 函式的時候,編碼時寫utf8,解碼時寫utf-8,有乙個短橫槓的區別。
python 連線mysql 使用sock 及引數
加引數指到mysql的配置 mysqldb.connect user root read default file etc my.conf 例如 conn mysqldb.connect host 10.3.18.142 user user,passwd pwd,db db,read default...
python爬蟲簡單入門
coding utf 8 from bs4 import beautifulsoup,soupstrainer from threading import lock,thread import sys,time,os from urlparse import urlparse,urljoin fro...
Python入門簡單操作
coding utf 8 created on fri oct 12 15 40 37 2018 author administrator import tensorflow as tf import numpy as np a np.array 1,2,3,4,5,6,7,8,9 dtype fl...