Communication between a Python server and a variety of clients (python/java/android)

Source: Internet
Author: User

Overview:

We are not always satisfied with the development of the client program because it is too limited. To break this constraint, all you have to do is write the server-side code. And how to communicate between the server and the client. The following will be a Python server for this, and the Python, Java, Android for the client to make a simple introduction.


server-side:

test_tcp_server.py

#!/usr/bin/env pythonfrom Socket Import *from time import ctimehost = ' PORT = 21567BUFSIZ = 1024ADDR = (HOST, PORT) tcpser Sock = socket (af_inet, Sock_stream) tcpsersock.setsockopt (Sol_socket, SO_REUSEADDR, 1) tcpsersock.bind (ADDR) Tcpsersock.listen (5) while True:    the print ' Waiting for connection ... '    tcpclisock, addr = tcpsersock.accept ()    print ' ... connected from: ', addr and        True:        data = TCPCLISOCK.RECV (bufsiz) if not        data:        break Tcpclisock.send (' Get your data:%s\n[%s] '% (data, CTime ()))            Tcpclisock.close        tcpsersock.close
for the above code, one thing we need to pay attention to. Tcpsersock.setsockopt (Sol_socket, SO_REUSEADDR, 1). Of course, if you are happy, you can not add this sentence, but the consequence of this sentence is that the above port can no longer be reused.

Client:1.python

#!/usr/bin/env pythonfrom Socket Import *host = ' input your HOST ip ' PORT = 21567BUFSIZ = 1024ADDR = (HOST, PORT) tcpclisock = Socket (af_inet, Sock_stream) Tcpclisock.connect (ADDR) while True:    data = raw_input (' > ')    if not data:        Break    tcpclisock.send (data)        Recv_data = Tcpclisock.recv (bufsiz)    if not recv_data:        break    Print Recv_datatcpclisock.close ()


2.Java

public static void Main (string[] args) throws IOException {                socket socket = new socket (HOST, PORT);        OutputStream outputstream = Socket.getoutputstream ();        Outputstream.write (("Hello server with Java"). GetBytes ());        Outputstream.flush ();        SYSTEM.OUT.PRINTLN (socket);                InputStream is = Socket.getinputstream ();        byte[] bytes = new byte[1024];        int n = is.read (bytes);        System.out.println (New String (bytes, 0, N));                Is.close ();        Socket.close ();    }

Run:



3.Android

public class Tcpclientactivity extends Activity {private int getlayoutresid () {return R.LAYOUT.ACTIVITY_TC    P_client;        } private Final int handler_msg_tell_recv = 0x124;    Private EditText mhostedittext = null;    Private EditText mportedittext = null;        Private EditText mcontentedittext = null;    Private Button Msubmitbutton = null;        Private Button Mcancelbutton = null;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                Setcontentview (Getlayoutresid ());    Initevent ();                } private void Initevent () {initviews ();    Setviews ();        } private void Initviews () {mhostedittext = (EditText) Findviewbyid (R.id.client_method_edittext);        Mportedittext = (EditText) Findviewbyid (R.id.client_mode_edittext);                Mcontentedittext = (EditText) Findviewbyid (R.id.client_content_edittext); Msubmitbutton = (Button) FindvieWbyid (R.id.client_submit_button);    Mcancelbutton = (Button) Findviewbyid (R.id.client_cancel_button);                        } private void Setviews () {Msubmitbutton.setonclicklistener (new Onclicklistener () {                @Override public void OnClick (View arg0) {String host = Mhostedittext.gettext (). toString ();                String port = Mportedittext.gettext (). toString ();                                String content = Mcontentedittext.gettext (). toString ();                Toast.maketext (Tcpclientactivity.this, Host + "," + Port + "," + content, 0). "Show ();            Startnetthread (Host, Integer.parseint (port), content);                }        }); Mcancelbutton.setonclicklistener (New Onclicklistener () {@Override public void OnClick (V            Iew arg0) {setemptyedittext ();    }        }); private void Startnetthread (final string host, final int port, final string data) {Thread thread = new Thread () {@Override public void run () {try {                    Socket socket = new socket (host, port);                    OutputStream outputstream = Socket.getoutputstream ();                    Outputstream.write (data). GetBytes ());                    Outputstream.flush ();                                        SYSTEM.OUT.PRINTLN (socket);                    InputStream is = Socket.getinputstream ();                    byte[] bytes = new byte[1024];                    int n = is.read (bytes);                                        System.out.println (New String (bytes, 0, n));                    Message msg = Handler.obtainmessage (handler_msg_tell_recv, New String (bytes, 0, n));                                        Msg.sendtotarget ();                    Is.close ();                Socket.close ();                } catch (Exception e) {}}};    Thread.Start ();       } Handler Handler = new Handler () {public void Handlemessage (Message msg) {Alertdialog.builder Builder            = new Alertdialog.builder (tcpclientactivity.this);            Builder.setmessage ("Data from server:" + (String) msg.obj);        Builder.create (). Show ();    };        };        private void Setemptyedittext () {Mhostedittext.settext ("");        Mportedittext.settext ("");    Mcontentedittext.settext (""); }}
Run:



Note: For the above client program, I think there is no problem. But if you just follow the steps above, you may not be able to run. Because of your firewall limitations in Linux, we usually choose to turn off the firewall in the experiment:

#/etc/init.d/iptables Stop

Communication between a Python server and a variety of clients (python/java/android)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.