Socket communication between Java and Python

Source: Internet
Author: User

Socket communication between Java and Python
Two programs on the network exchange data through a two-way communication connection. one end of this two-way link is called a Socket. Socket supports many protocols. Here we mainly introduce Socket programming based on the TCP/IP protocol family.

First, the IP protocol family determines the socket address type. The corresponding address must be used in communication. AF_INET (AF indicates Adress Family) indicates the combination of ipv4 address (32-bit) and port number (16-bit.

Based on the transmission protocol, it is divided into: streaming Socket (SOCK_STREAM) and datagram Socket (SOCK_DGRAM ):
Stream SOCK_STREAM is a connection-oriented Socket for connection-oriented TCP Service applications; datagram SOCK_DGRAM is a connectionless Socket, which corresponds to connectionless UDP Service applications;

Let's take a look at the Socket communication in Java. In the Java environment, Socket programming mainly refers to Network Programming Based on TCP/IP, and the corresponding Socket API is mainly these two types of Socket and ServerSocket. A server socket corresponds to multiple client sockets. In this case, it must be implemented with multiple threads. the accept () package is in the loop, polling the listening client, and then each time you establish a connection to the socket object as a parameter to create a new thread. If you only have one client, it doesn't matter.

The following is a simple example. Because text communication is the most commonly used, we will introduce the implementation of text communication. Of course, binary streams can also be used directly, such as file transfer.

<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Authorization + zvHG9yBTb2NrZXQ8L3A + cjxwp1_vcd4kphbyzsbjbgfzcz0 = "brush: java;"> import java. io. bufferedReader; import java. io. IOException; import java. io. inputStreamReader; import java. io. printWriter; import java.net. serverSocket; import java.net. socket; public class DataSocketServer {public static void main (String [] args) {try {ServerSocket server = new ServerSocket (5000); System. out. p Rintln ("Server start! "); Socket socket = server. accept (); // block wait until a client socket comes over System. out. println (" There comes a socket! "); BufferedReader in = new BufferedReader (new InputStreamReader (socket. getInputStream (); // input, from client PrintWriter out = new PrintWriter (socket. getOutputStream (); // output, to the client System. out. println (in. readLine (); // print the character sent from the client socket, by line (\ n, \ r, or \ r \ n) out. println ("Server reponse! Pai_^ "); out. flush (); // to client, output socket. close (); server. close (); System. out. println (" Server end! ");} Catch (IOException e) {e. printStackTrace ();}}}Java client Socket

Import java. io. bufferedReader; import java. io. IOException; import java. io. inputStreamReader; import java. io. printWriter; import java.net. socket; import java.net. unknownHostException; public class TestSocketClient {public static void main (String [] args) {try {Socket socket = new Socket ("127.0.0.1", 5000); System. out. println ("Client start! "); PrintWriter out = new PrintWriter (socket. getOutputStream (); // output, to server socketBufferedReader in = new BufferedReader (new InputStreamReader (socket. getInputStream (); // input, from server socketout. println ("Client request! :-) "); Out. flush (); // fl the buffer output to the server System. out. println (in. readLine (); // print the System string sent by the server. out. println ("Client end! "); Socket. close () ;}catch (UnknownHostException e) {e. printStackTrace () ;}catch (IOException e) {e. printStackTrace ();}}}

Python client Socket (Python 3.4)

Import socket sock = socket. socket (socket. AF_INET, socket. SOCK_STREAM) sock. connect ('localhost ', 5000) print ('client start! ') Sock. send (bytes ('client :) \ n', encoding = 'utf-8') # str type-> bytes type, send, \ n never miss, because the preceding server reads print (str (sock. recv (1024), encoding = 'utf-8') # bytes type-> str type, accept sock. close () print ('client end! ')

Here we will focus on the conversion of the bytes type and str type in Python. In Python3, the text and binary data are clearly distinguished, and the text is always Unicode as the str type, binary is represented by bytes type. Clear division is more conducive to the readability and correctness of the program.

Of course, Server Socket can also be written in Python. Specify the protocol and type socket first. socket (family, type), bind the address and port, and then listen. The basic principle is the same as above.

Address: http://blog.csdn.net/thisinnocence

Related Article

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.