Skip to content

Latest commit

 

History

History
110 lines (86 loc) · 2.6 KB

18.md

File metadata and controls

110 lines (86 loc) · 2.6 KB

第18节 Python里的socket编程

❤️💕💕计算机网络--TCP/IP 学习。Myblog:http://nsddd.top


[TOC]

Python里的socket编程

UDP编程

客户端程序

from socket import *
# 要访问的服务器地址和端口号
serverName = 'localhost'
serverPort = 8080
# AF_INEF指定了IPv4 SOCK_DGRAM指定了UDP协议
clientSocket = socket(AF_INEF,SOCK_DGRAM)
# 发送数据
message = raw_input('Input lowercase sentence:')
clientSocket.sendto(message,(serverName,serverPort))
# modifiedMessage存响应报文,serverAddress存响应源地址 缓存长度2048
modifiedMessage,serverAddress = clientSocket.recvfrom(2048)
print modifiedMessage
# 关闭连接
clientSocket.close()

服务器程序

from socket import *
# 要监听的端口号
serverPort = 8080
# AF_INEF指定了IPv4 SOCK_DGRAM指定了UDP协议
serverSocket = socket(AF_INEF,SOCK_DGRAM)
serverSocket.bind('',serverPort)
print "Ready..."
while True:
    message,clientAddress = serverPort.recvfrom(2048)
    modifiedMessage = message.upper() # 全部转为大写
    serverSocket.sendto(modifiedMessage, clientAddress)

TCP编程

客户端程序

from socket import *
# 要访问的服务器地址和端口号
serverName = 'localhost'
serverPort = 8080
# AF_INEF指定了IPv4 SOCK_STREAM指定了TCP协议
clientSocket = socket(AF_INEF,SOCK_STREAM)
# 创建TCP连接
clientSocket.connect((serverName,serverPort))
# 发送数据
message = raw_input('Input lowercase sentence:')
clientSocket.send(message)
# modifiedMessage存响应报文,serverAddress存响应源地址 缓存长度2048
modifiedMessage = clientSocket.recvfrom(2048)
print modifiedMessage
# 关闭连接
clientSocket.close()

服务器程序

from socket import *
# 要监听的端口号
serverPort = 8080
# AF_INEF指定了IPv4 SOCK_STREAM指定了TCP协议
serverSocket = socket(AF_INEF,SOCK_STREAM)
serverSocket.bind('',serverPort)
# 设置可接受的TCP连接数
serverSocket.listen(1)
print "Ready..."
while True:
    # 接受连接
    connectionSocket, addr = serverSocket.accpet()
    message = serverPort.recvfrom(2048)
    modifiedMessage = message.upper() # 全部转为大写
    connectionSocket.send(modifiedMessage)
    connectionSocket.close()

END 链接