Search code examples
pythonsocketsencodingraspberry-pi3persian

Sending persian string with socket from python to python


I want to send an Persian(farsi) string with socket from python to another python in raspberry. I see some question mark in terminal and when write that in a txt file i see ÇÝÔÇÑ characters(for a word). server code:

# -*- coding: cp1256 -*-
import sys
import time
import os
import SocketServer
import thread
import os.path
import webbrowser
import RPi.GPIO as GPIO



    class MyTCPHandler(SocketServer.BaseRequestHandler):
        """
            The reques

t handler class for our server.

        It is instantiated once per connection to the server, and must
        override the handle() method to implement communication to the
        client.
        """

    def handle(self):
        try:
            # self.request is the TCP socket connected to the client
            self.data = self.request.recv(1024).strip()
            print "{} wrote:".format(self.client_address[0])


            text2=self.data

            print type(text2)

            text_file = open("Output.txt", "w")
            text_file.write(text2)
            text_file.close()
            completeURL="http://10.7.6.172/GanjSearch.aspx?q=/%s/" %text2
            print completeURL
            webbrowser.open(completeURL) 

        except Exception, e:
            print type(e)
            print e


if __name__ == "__main__":
    HOST, PORT = "192.168.1.55", 9998
    # Create the server, binding to localhost on port 9999
    try:
        server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
        # Activate the server; this will keep running until you
        # interrupt the program with Ctrl-C
        server.serve_forever()
    except Exception, e:
            print type(e)
            print e

client code:

a="persian-word"
socket.sendall(a)

what must i do?


Solution

  • I use # -*- coding: utf-8 -*- instead of # -*- coding: cp1256 -*- in top of both code(client and server). so without used of decode and encode functions, it work correctly.