菜鸟学堂 -【Python Socket 】

来源:互联网 发布:部门预算软件 编辑:程序博客网 时间:2024/06/10 06:32
Python 3.2.2(default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win
32

Type "help", "copyright", "credits" or "license" for more information.


一:官方文档:

http://docs.python.org/py3k/library/socket.html

socket — Low-level networking interface


二:example


Server start:

F:\workspace_android\test\com\nagat\socket>Server.py
listen:...............
host: localhost ,post: 12345
wait.................
Connected by ('127.0.0.1', 50710)
其他数据:fs
Connected by ('127.0.0.1', 50711)
数据:hi

Client:

F:\workspace_android\test\com\nagat\socket>Client.py fs
from server to client: 其他数据:fs

F:\workspace_android\test\com\nagat\socket>Client.py hi
from server to client: 你好,世界

 

三:example code

server:

import socketHOST = 'localhost'                 # Symbolic name meaning all available interfacesPORT = 12345              # Arbitrary non-privileged ports = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.bind((HOST, PORT))s.listen(1)print("listen:............... ")print("host:",HOST,",post:",PORT)print("wait.................")while 1:    conn, addr = s.accept()    print ('Connected by', addr)    while 1:        data = conn.recv(1024)#        print(repr(data))#        print(str(data,"utf-8"))        if not data: break                if  data == bytes("hi","utf-8"):            print("数据:"+str(data,"utf-8"))            conn.sendall(bytes("你好,世界","utf-8"))        else :            print("其他数据:"+str(data,"utf-8"))            conn.sendall(bytes("其他数据:"+str(data,"utf-8"),"utf-8"))    conn.close()


 

Client:

import socket,sys#print(sys.argv)#print(sys.argv[1])HOST = 'localhost'    # The remote hostPORT = 12345              # The same port as used by the servers = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.connect((HOST, PORT))s.sendall(bytes(sys.argv[1],"utf-8"))data = s.recv(1024)s.close()print('from server to client:', str(data,"utf-8"))


四:除了字符串还能发送别的不?