python socket编程(socket)
2024-08-31 08:39:46
代码如下:
server端:
import socket
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host=socket.gethostname()
port=1234
s.bind((host,port))
s.listen(5)
while True:
c,addr=s.accept()
print("got connecion from:",addr)
while True:
msg=c.recv(1024).decode()
print("msg:",msg)
if not msg:
break
data="hello"
c.send(data.encode("utf-8"))
c.close() client端: import socket
host="server_name or ip"
port=1234
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((host,port))
while True:
data=input("please input:")
if not data:
break
s.send(data.encode("utf-8"))
msg=s.recv(1024).decode()
if not msg:
break
print(msg)
s.close()
注意点:
1.port最好用大于1024的值。
2.client中的host要用server的IP或者主机名
3.数据的编码解码 可能报错及分析
1.ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
原因分析:服务器未启动
2.ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
原因分析: 服务器突然关掉了 3. ConnectionAbortError: [WinError 10053] An established connection was aborted by the sofeware in youor host machine
原因分析:server端的代码在接收一个msg,发送一个data后就关闭了connection。应该在程序中加while循环,让不断的发送和接收 4.OsError: [WinError 10049] The requested address is not valid in its context
原因分析:代码中服务器hostname不对
最新文章
- unity3d android 优化
- Linux C++ 调试神技--如何将Linux C++ 可执行文件逆向工程到Intel格式汇编
- Matlab 的reshape函数
- VNC与Windows之间的复制粘贴
- 【Android测试】【第十一节】Uiautomator——简介
- CSS实现图片快速等比例缩放,效果佳
- 教程-Delphi7 自带控件安装对应表
- 百度编辑器1.4.3 .net版在vs2008的使用方法
- 图片延迟加载技术-Lazyload的应用
- 简单DP-艰难取舍
- Caused by: java.lang.NoClassDefFoundError: org/hibernate/cfg/Configuration
- CSS揭秘—灵活的背景图(三)
- 一个漂亮的php验证码类
- Linux免密码登录设置
- MySQL 5.6下table_open_cache参数合理配置详解
- jsp servlet 的 请求转发和重定向
- Codeforces 932G Palindrome Partition 回文树+DP
- Python 时间
- bzoj5019: [Snoi2017]遗失的答案
- python 将字符串转换成字典dict的各种方式总结
热门文章
- Python与数据结构[1] ->; 栈/Stack[0] ->; 链表栈与数组栈的 Python 实现
- Spring/Spring MVC/Spring Boot实现跨域
- Systems Performance: Enterprise and the Cloud 读书笔记系列
- Java 使用IE浏览器下载文件,文件名乱码问题
- git只拉取github部分代码的方法
- JAVA之抽象类与抽象方法
- Java获取运行环境信息
- wp8手机浏览器项目
- 2017.3.31 spring mvc教程(七)多视图控制器
- Picasso自定义缓存目录