java Network programming using socket(1)

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);
            }

        }
    }
}
时间: 2024-09-29 04:12:19

java Network programming using socket(1)的相关文章

分享:Foundations of Python Network Programming(3rd) 英文版pdf 下载

Foundations of Python Network Programming Third Edition 下载http://www.amazon.com/Foundations-Python-Network-Programming-Brandon/dp/1430258543这本书是2014年底出版的,基于最新的 python3.4 版本.配书源码链接https://github.com/brandon-rhodes/fopnp 目录 Chapter 1: Introduction to C

【learning log】Linux network programming

DNS host entry 包含 DNS database 中有关某一 domin name 或 ip address 的 DNS 信息. 1 struct hostent{ 2 char *h_name; 3 char *h_aliases; 4 int h_addrtype; 5 int h_length; 6 char **h_addr_list; 7 }; hostinfo 程序, 用来从 ip 或 domin name 解析 DNS info. 1 /*This program is

我看不下去鸟。。。。Java和C#的socket通信真的简单吗?

这几天在博客园上看到好几个写Java和C#的socket通信的帖子.但是都为指出其中关键点. C# socket通信组件有很多,在vs 使用nuget搜索socket组件有很多类似的.本人使用的是自己开发的一套组件. Java socket通信的组件也有很多,常用的大多数都是用的mina或者netty.游戏行业使用也是居多. 关于socket的底层写法,实在太多,我就不在BB. 这里我想说,C#和C++或者叫VC++把是使用小端序作为字节序.而java使用的是大端序作为字节序. 也就是说比如一个

Java NetWork笔记

java Network编程所需要的包:java.net java.io java.lang java.net中所需要的类或接口:Socket ServerSocket DatagramSocket DatagramPacket URL URLConnection java.io中所需要的类或接口:InputStream/OutputStream BufferedInputStream/BufferedOutputStream DataInputStream/DataOutputStream B

Java和C#的socket通信相关(转)

这几天在博客园上看到好几个写Java和C#的socket通信的帖子.但是都为指出其中关键点. C# socket通信组件有很多,在vs 使用nuget搜索socket组件有很多类似的.本人使用的是自己开发的一套组件. Java socket通信的组件也有很多,常用的大多数都是用的mina或者netty.游戏行业使用也是居多. 关于socket的底层写法,实在太多,我就不在BB. 这里我想说,C#和C++或者叫VC++把是使用小端序作为字节序.而java使用的是大端序作为字节序. 也就是说比如一个

TCP 、UDP网络编程作业代写、代写C 语言 TCP程序 Network Programming using C

TCP .UDP网络编程作业代写.代写C 语言 TCP程序Network Programming using COverview? This homework is due by 11:59:59 PM on Thursday, April 26, 2018.? This homework will count as 8% of your final course grade.? This homework is to be completed individually. Do not shar

Professional iOS Network Programming Connecting the Enterprise to the iPhone and iPad

Book Description Learn to develop iPhone and iPad applications for networked enterprise environments The iPhone and iPad have made a powerful impact on the business world. Developers creating iOS apps for the enterprise face unique challenges involvi

Java学习(六):Socket编程实例

Socket又称"套接字",应用程序通常通过"套接字"向网络发出请求或者应答网络请求. Java已经简化了Socket的编程接口.Java提供了ServerSocket来对其进行支持.事实上当创建该类的一个实例对象并提供一个端口资源,就建立了一个固定位置可以让其他计算机来访问了,如:ServerSocket server=new ServerSocket(6789);       这里稍微要注意的是端口的分配必须是唯一的.因为端口是为了唯一标识每台计算机唯一服务的.

【转】JAVA网络编程之Socket用法

JAVA网络编程之Socket用法 分类: JAVA2012-08-24 15:56 710人阅读 评论(0) 收藏 举报 在客户/服务器通信模式中,客户端需要主动建立与服务器连接的Socket,服务器端收到客户端的连接请求,也会创建与客户端连接的Socket.Socket可以看做是通信连接两端的收发器,客户端和服务店都通过Socket来收发数据. 1.构造Socket public Socket() 通过系统默认类型的 SocketImpl 创建未连接套接字 public Socket(Str