+ -
当前位置:首页 → 问答吧 → 求高手指教,python中C/S传输字符串问题

求高手指教,python中C/S传输字符串问题

时间:2011-12-06

来源:互联网

问题如下:代码编译过可以通过,server和client传输时,直接传一个字符串可以,但我将它换成文本框中
的内容connection.send(text)就传不过去了,我想问下是不是send中text参数不应该这么传进去,以前一直
用c/c++,刚接触python,求多指教。

我的server.py
Python code

from Tkinter import *
import socket

def on_clicked():
  while True:
      connection, address = sock.accept()
      try:
        connection.settimeout(4)
        buf = connection.recv(1024)
        label['text'] = buf
        connection.send(text)
      except socket.timeout:
        print 'time out'
      connection.close()
root = Tk(className = 'Server')
label = Label(root)
label['text'] = 'IP'
label.pack()

text = StringVar()
text.set('input ip')
entry = Entry(root)
entry['textvariable'] = text
entry.pack()

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#sock.bind((text, 8000))
sock.bind(('localhost', 8001))
sock.listen(5)

button = Button(root)
button['text'] = 'OK'
button['command'] = on_clicked
button.pack()

root.mainloop() 






client.py

Python code

from Tkinter import *
import socket
import time

def on_clicked():
    sock.connect(('localhost', 8001))
    time.sleep(2)
    sock.send(text)
    recv = sock.recv(1024)
    label['text'] = recv
    sock.close()

root = Tk(className = 'Client')
label = Label(root)
label['text'] = 'connect to...'
label.pack()

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
text = StringVar()
text.set('IP')
entry = Entry(root)
entry['textvariable'] = text
entry.pack()
button = Button()
button['text'] = 'connect'
button['command'] = on_clicked
button.pack()

root.mainloop()


作者: threefeets   发布时间: 2011-12-06

阅读出错信息。

作者: iambic   发布时间: 2011-12-06

引用 1 楼 iambic 的回复:

阅读出错信息。


我看过了,是这样说的Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1410, in __call__
  return self.func(*args)
  File "Client.py", line 8, in on_clicked
  sock.send(text)
TypeError: send() argument 1 must be string or buffer, not instance
Traceback (most recent call last):
  File "Client.py", line 31, in <module>
  root.mainloop()
  File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1017, in mainloop
  self.tk.mainloop(n)

但能说下python中send参数如何传进去么?我需要将text中的字符串传进去,不是send(text)???

作者: threefeets   发布时间: 2011-12-06

传的参数类型不对,我试了可以显示多行的。
像类似这样:

label['text'] = str(buf)

sock.send(str(text))

可以在服务器端程序label部件中显示多行文本,就是跟客户端的Text部件输入的内容一样的显示

作者: askandstudy   发布时间: 2011-12-06

引用 3 楼 askandstudy 的回复:

传的参数类型不对,我试了可以显示多行的。
像类似这样:

label['text'] = str(buf)

sock.send(str(text))

可以在服务器端程序label部件中显示多行文本,就是跟客户端的Text部件输入的内容一样的显示


还是不行啊
我将发送数据改成这样了
Python code

    text_string = text.get()
    sock.send(text_string)



客户端可以接收server发送过来的数据了,但
server不知为什么没接收到client 的数据

作者: threefeets   发布时间: 2011-12-06

获取不到。。。是不是传递的值就是空的呢?

作者: zheng_j_c   发布时间: 2011-12-06