Java Network Programming using socket (1)

Source: Internet
Author: User

Java supports stream-based communication and packet-based Communication,and the first is universal.
Create ServerSocket
1.Create serversocket

ServerSocket serversocket=new ServerSocket (port);

2.Listen to the Connect

Socket socket=serversocket.accept ();

3.We need create inputstream and outputstream to transmit data

InputStream Inputfromclient=socket.getinputsream ();
OutputStream Outputtoclient=socket.getoutputstream ();

(We can also use DataInputStream and DataOutputStream, BufferedReader and PrintWriter to get the data types is int,double and string.)

Create Client Socket
1.Create Client Socket

Socket socket=new socket (servername,port);

(The serverName can be host name or the host IP address.)
2.We need create inputstream and outputstream to transmit data

Inputsream Inputfromserver=socket.getinputstream ();
OutputStream Outputtoserver=socket.getoutputstream ();

(We can also use DataInputStream and DataOutputStream, BufferedReader and PrintWriter to get the data type is int,double or string.)

Now,there is a example that Client send radius to server and server compute area and return to Client.

Server.java

ImportJava.awt.BorderLayout;ImportJava.io.DataInputStream;ImportJava.io.DataOutputStream;ImportJava.io.IOException;ImportJava.net.ServerSocket;ImportJava.net.Socket;ImportJava.util.Date;ImportJavax.swing.JFrame;ImportJavax.swing.JScrollPane;ImportJavax.swing.JTextArea; Public  class Server extends JFrame {    PrivateJTextArea Jta=NewJTextArea (); Public Static void Main(string[] args) {NewServer (); } Public Server() {setlayout (NewBorderLayout ()); AddNewJScrollPane (JTA), borderlayout.center); Settitle ("Server"); SetSize ( -, -);        Setdefaultcloseoperation (Jframe.exit_on_close); SetVisible (true);Try{//create a server socketServerSocket serversocket=NewServerSocket (8000); Jta.append ("Server started at"+NewDate () +"\ n");//listen for a connection requestSocket socket=serversocket.accept ();//create data input and output streamsDataInputStream inputfromclient=NewDataInputStream (Socket.getinputstream ()); DataOutputStream outputtoclient=NewDataOutputStream (Socket.getoutputstream ()); while(true) {//receive radius from the client                DoubleRadius=inputfromclient.readdouble ();//compute Area                DoubleArea=radius*radius*math.pi;//send area back to the clientOutputtoclient.writedouble (area); Jta.append ("Radius received from client:"+radius +' \ n '); Jta.append ("area found:"+area+' \ n '); }        }Catch(IOException ex)        {System.err.println (ex); }    }}

Client.java

ImportJava.awt.BorderLayout;ImportJava.awt.event.ActionEvent;ImportJava.awt.event.ActionListener;ImportJava.io.DataInputStream;ImportJava.io.DataOutputStream;ImportJava.io.IOException;Importjava.net.InetAddress;ImportJava.net.Socket;ImportJavax.swing.JFrame;ImportJavax.swing.JLabel;ImportJavax.swing.JPanel;ImportJavax.swing.JScrollPane;ImportJavax.swing.JTextArea;ImportJavax.swing.JTextField; Public  class Client extends JFrame {    //text filed for receiving RADIUS    PrivateJTextField jtf=NewJTextField ();//text area to display contents    PrivateJTextArea Jta=NewJTextArea ();//io streams    PrivateDataOutputStream Toserver;PrivateDataInputStream fromserver; Public Static void Main(string[] args) {NewClient (); } Public Client(){//panel Panel to hold the label and text fieldJPanel panel=NewJPanel (); Panel.setlayout (NewBorderLayout ()); Panel.add (NewJLabel ("Enter radius"), borderlayout.west);        Panel.add (Jtf,borderlayout.center);        Jtf.sethorizontalalignment (Jtextfield.right); SetLayout (NewBorderLayout ());        Add (Panel,borderlayout.north); AddNewJScrollPane (JTA), borderlayout.center); Jtf.addactionlistener (NewTextfieldlistener ()); Settitle ("Client"); SetSize ( -, -);        Setdefaultcloseoperation (Jframe.exit_on_close); SetVisible (true);//it is necessary to show the frame here        Try{//create a socket to connect to the serverSocket socket=NewSocket ("localhost",8000);//socket Socket =new socket ("130.254.204.36", 8000);            //socket Socket =new socket ("Drake. Armstrong.edu ", 8000);System.out.println ("Local port:"+socket.getlocalport ());//test inetaddressInetAddress inetaddress=socket.getinetaddress (); System.out.println ("Client s host name is"+inetaddress.gethostname ()); System.out.println ("Client's IP address is"+inetaddress.gethostaddress ());//            //create an input stream to receive data from the serverFromserver=NewDataInputStream (Socket.getinputstream ());//create an output stream to send data from the serverToserver=NewDataOutputStream (Socket.getoutputstream ()); }Catch(IOException ex) {Jta.append (ex.tostring () +' \ n '); }    }Private  class Textfieldlistener implements ActionListener{         Public void actionperformed(ActionEvent e) {Try{//get the radius from the text field                DoubleRadius=double.parsedouble (Jtf.gettext (). Trim ());//send The RADIUS to the serverToserver.writedouble (RADIUS); Toserver.flush ();//get area from the server                DoubleArea=fromserver.readdouble ();//display to the text serverJta.append ("Radius is"+radius+"\ n"); Jta.append ("area received from the server is"+area +' \ n '); }Catch(IOException ex)            {System.err.println (ex); }        }    }}

Java Network Programming using socket (1)

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.