前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python简单socket

python简单socket

作者头像
py3study
发布2020-01-13 12:59:58
2850
发布2020-01-13 12:59:58
举报
文章被收录于专栏:python3python3
  1. clinet端
  2. #! /usr/bin/env python # -*-coding: utf-8-*- #这段代码是clinet端 import socket   #for sockets import sys  #for exit try:     #create an AF_INET, STREAM socket (TCP)     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error, msg:     print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1]     sys.exit(); print 'Socket Created' host = '192.168.1.20' port = 8888 try:     remote_ip = socket.gethostbyname( host ) except socket.gaierror:     #could not resolve     print 'Hostname could not be resolved. Exiting'     sys.exit() print 'Ip address of ' + host + ' is ' + remote_ip #Connect to remote server s.connect((remote_ip , port)) print 'Socket Connected to ' + host + ' on ip ' + remote_ip
  3. server端
  4. #! /usr/bin/env python # -*- coding: utf-8 -*- import socket import sys from thread import * HOST = ''   # Symbolic name meaning all available interfaces PORT = 8888 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print 'Socket created' #Bind socket to local host and port try:     s.bind((HOST, PORT)) except socket.error , msg:     print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]     sys.exit() print 'Socket bind complete' #Start listening on socket s.listen(10) print 'Socket now listening' #Function for handling connections. This will be used to create threads def clientthread(conn):     #Sending message to connected client     conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string     #infinite loop so that function do not terminate and thread do not end.     while True:         #Receiving from client         data = conn.recv(1024)         reply = 'OK...' + data         if not data:             break         conn.sendall(reply)     #came out of loop     conn.close() #now keep talking with the client while 1:     #wait to accept a connection - blocking call     conn, addr = s.accept()     print 'Connected with ' + addr[0] + ':' + str(addr[1])     #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.     start_new_thread(clientthread ,(conn,)) s.close()
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-08-08 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档