关于Python的服务器客户端交互问题
黄舟
黄舟 2017-04-18 10:19:23
0
1
619

如何用加代码可以使TCP客户端的消息发送到TCP服务器上并print出来?

#!/usr/bin/env python

from socket import *

HOST=''
PORT=21567
ADDR=(HOST,PORT)

tcpSerSock=socket(AF_INET,SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)

while True:
    print 'waiting for connection...'
    tcpCliSock,addr=tcpSerSock.accept()
    print '...connected from:',addr
    
while True:
    data=tcpCliSock.recv(1024)
    if not data:
        break
    tcpCliSock.send(data)

tcpCliSock.close()
tcpSerSock.close()

#!/usr/bin/env python

from socket import *

HOST='localhost'
PORT=21567
ADDR=(HOST,PORT)

tcpCliSock=socket(AF_INET,SOCK_STREAM)
tcpCliSock.connect(ADDR)

while True:
    data=raw_input('>')
    if not data:
        break
    tcpCliSock.send(data)
    data=tcpCliSock.recv(1024)
    if not data:
        break
    print data

tcpCliSock.close()

这是我的客户端和服务器代码,我不知道如何下手去改,现在就反馈主机序列号

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

Antworte allen(1)
巴扎黑
# -*- coding: utf-8 -*-

from socket import *
from time import ctime

HOST = 'localhost'
PORT = 12345
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(2)

while True:
  tcpSerSock.connect_ex(ADDR)
  print 'waiting for connection...'
  tcpCliSock, addr = tcpSerSock.accept()
  print '...connected from:', addr

  while True:
    data = tcpCliSock.recv(BUFSIZ)
    print data,len(data)
    if not data:
      break
    tcpCliSock.send('[%s] %s' % (ctime(), data))

tcpCliSock.close()
tcpSerSock.close()
# -*- coding: utf-8 -*-

from socket import *

HOST = '121.40.77.203'
PORT = 12345
BUFSIZ = 1024
ADDR = (HOST, PORT)

tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
while True:
  data = open('C:\\Users\\gzx\\Desktop\\client_net_dict.txt').read()
  if not data:
    break
  tcpCliSock.sendall(data)
  data = tcpCliSock.recv(1024)
  if not data:
    break
  print len(data)

tcpCliSock.close()
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage