java Network programming using socket(1),programmingusing

來源:互聯網
上載者:User

java Network programming using socket(1),programmingusing

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 are 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 are int,double or string.)

Now,there is an example that Client send radius to Server and Server compute area and return to Client.

Server.java

import java.awt.BorderLayout;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;import java.util.Date;import javax.swing.JFrame;import javax.swing.JScrollPane;import javax.swing.JTextArea;public class Server extends JFrame {    private JTextArea jta=new JTextArea();    public static void main(String[] args) {        new Server();    }    public Server() {        setLayout(new BorderLayout());        add(new JScrollPane(jta),BorderLayout.CENTER);        setTitle("Server");        setSize(500,300);        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        setVisible(true);        try{            //Create a server socket            ServerSocket serverSocket=new ServerSocket(8000);            jta.append("Server started at "+new Date() +"\n");            //Listen for a connection request            Socket socket=serverSocket.accept();            //Create data input and output streams            DataInputStream inputFromClient=new DataInputStream(socket.getInputStream());            DataOutputStream outputToClient=new DataOutputStream(socket.getOutputStream());            while (true) {                //Receive radius from the client                double radius=inputFromClient.readDouble();                //Compute area                double area=radius*radius*Math.PI;                //Send area back to the client                outputToClient.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

import java.awt.BorderLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.net.InetAddress;import java.net.Socket;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JScrollPane;import javax.swing.JTextArea;import javax.swing.JTextField;public class Client extends JFrame {    //Text filed for receiving radius    private JTextField jtf=new JTextField();    //Text area to display contents    private JTextArea jta=new JTextArea();    //IO streams    private DataOutputStream toServer;    private DataInputStream fromServer;    public static void main(String[] args) {        new Client();    }    public Client(){        //Panel panel to hold the label and text field         JPanel panel=new JPanel();        panel.setLayout(new BorderLayout());        panel.add(new JLabel("Enter radius"),BorderLayout.WEST);        panel.add(jtf,BorderLayout.CENTER);        jtf.setHorizontalAlignment(JTextField.RIGHT);        setLayout(new BorderLayout());        add(panel,BorderLayout.NORTH);        add(new JScrollPane(jta),BorderLayout.CENTER);        jtf.addActionListener(new TextFieldListener());        setTitle("Client");        setSize(500,300);        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        setVisible(true);//It is necessary to show the frame here        try {            //Create a socket to connect to the server            Socket socket=new Socket("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 InetAddress            InetAddress 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 server            fromServer=new DataInputStream(socket.getInputStream());            //Create an output stream to send data from the server            toServer=new DataOutputStream(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                double radius=Double.parseDouble(jtf.getText().trim());                //Send the radius to the server                toServer.writeDouble(radius);                toServer.flush();                //Get area from the server                double area=fromServer.readDouble();                //display to the text server                jta.append("Radius is "+radius+"\n");                jta.append("Area received from the server is "+area +'\n');            } catch (IOException ex) {                System.err.println(ex);            }        }    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.