python socket程式設計---從使用Python開發一個Socket示例說到開發者的思維和習慣問題
阿新 • • 發佈:2019-01-28
- python沒有用過,怎麼辦呢?
- 我用過python,可是我們開發過socket方面的應用?
- 我還不知道socket是什麼東西呢?
- socket大概我記得,套接字嗎,ip+port,具體的tcp和udp我不不太清楚。
- 語言的語法,語言的基本結構(順序,選擇,迴圈)。
- 技術的基礎理論,例如,資料庫理論,檔案系統理論,今天我們演示用的socket通訊理論。
- import socket
- HOST='192.168.0.37'
- PORT=50000
- BUFFER=4096
- sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
- sock.bind((HOST,PORT))
- sock.listen(0)
- print('tcpServer listen at: %s:%s\n\r' %(HOST,PORT))
- whileTrue:
- client_sock,client_addr=sock.accept()
- print('%s:%s connect' %client_addr)
- whileTrue:
- recv=client_sock.recv(BUFFER)
- ifnot recv:
- client_sock.close()
- break
- print('[Client %s:%s said]:%s' % (client_addr[0],client_addr[1],recv))
- client_sock.send('tcpServer has received your message')
- sock.close()
- import socket
- HOST='192.168.0.37'
- PORT=50000
- BUFFER=4096
- sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
- sock.connect((HOST,PORT))
- sock.send('hello, tcpServer!')
- recv=sock.recv(BUFFER)
- print('[tcpServer said]: %s' % recv)
- sock.close()
- import socket
- HOST='192.168.0.37'
- PORT=50001
- BUFFER=4096
- sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
- sock.bind((HOST,PORT))
- #sock.listen(0)
- print('tcpServer listen at: %s:%s\n\r' %(HOST,PORT))
- whileTrue:
- #client_sock,client_addr=sock.accept()
- #print('%s:%s connect' %client_addr)
- whileTrue:
- recv,client_addr=sock.recvfrom(BUFFER)
- ifnot recv:
- break
- print('[Client %s:%s said]:%s' % (client_addr[0],client_addr[1],recv))
- sock.sendto('tcpServer has received your message',client_addr)
- sock.close()
- socket.SOCK_DGRAM
- #!/usr/bin/env python
- # -*- coding: UTF-8 -*-
- import socket
- HOST='192.168.0.37'
- PORT=50001
- BUFFER=4096
- sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
- sock.connect((HOST,PORT))
- sock.send('hello, tcpServer!')
- recv=sock.recv(BUFFER)
- print('[tcpServer said]: %s' % recv)
- sock.close()