Java Network programming

Source: Internet
Author: User

Introduction to Java Network Programming network programming
通过使用套接字来达到进程间通信目的的编程就是网络编程网络编程最重要的两点1、定位目标主机(ip地址和端口)2、如何传输数据(协议)
The two main models of network programming are based on the TCP programming model
面向连接相对可靠传输协议编程TCP:传输控制协议案列模型:打电话通话要点:基于TCP网络编程的核心在于建立连接,通过连接里获得流对象来实现数据的传输的目的。备注:TCP编程的核心在于连接,以及从连接获得的流对象。

Based on the UDP programming model
面向无连接不是很可靠的传输协议UDP:用户数据报协议案列模型:发送短信、日常寄送包裹要点:基于UDP网络编程的核心在于构建数据包对象,从DatagramSocket对象中发送和接收数据包对象。备注:UDP编程的核心在于数据报中

Java Network Programming Foundation Class and Core class Java network programming base class

InetAddress class

InetAddress对象表示IP地址,由于java是面向对象编程的语言,所以为了给IP匹配就以InetAddress来表示IP地址。直接使用字符串表示IP地址也没关系。

URL class

URL对象表示同意资源定位符,同InetAddress类似,url同样也可以使用字符串表示,只不过java是面向对象语言因此使用了URL类。

URLConnection class

URLConnection是一个抽象类,表示一个连接,其主要实现由HttpURLConnection类,http连接。发送请求时就会使用到这个类。
Java Network Programming Core class

Socket sockets

A socket is an endpoint for communication between two machines.

ServerSocket Server sockets

This class implements server sockets. A server socket waits for requests to come in over the network. It performs some operation备注:可以把Socket和ServerSocket简单理解为连接端点。

Datagramsocket Datagram sockets

This class represents a socket for sending and receiving datagram packets.A datagram socket is the sending or receiving point for a packet delivery service. Each packet sent or received on a datagram socket is individually addressed and routed.Multiple packets sent from one machine to another may be routed differently, and may arrive in any order.备注:理解为邮局

Datagrampacket Data Report

This class represents a datagram packet.备注:理解为数据包裹
Java Network Programming Chat program TCP-based chat

Client-side code

/** * Console input information, chat applet. * * @author Xuyi3 * @ July 18, 2016 @ 9:35:08 * @Client2 * @ Function Description:<br> * @ Spring Breeze ten miles than you * @ Note */public class Client {public S tatic void Main (string[] args) throws Exception {//client new socket object, host address and Port must be established socket SOCKET = new Socket ("1        92.168.1.187 ", 9999);        Gets the connected input stream InputStream in = Socket.getinputstream () through the socket object;        Get the connected output stream through the socket object OutputStream out = Socket.getoutputstream ();        Use a more convenient buffer wrapper stream to operate BufferedReader reader = new BufferedReader (new InputStreamReader (in));        BufferedWriter writer = new BufferedWriter (new OutputStreamWriter (out));        Console input stream Scanner Scanner = new Scanner (system.in);            while (true) {//Output information to server System.out.print ("client:");            String line = null;            line = Scanner.nextline ();            Writer.write (line);            The following two steps are important, and not writing will keep each other's input stream blocked.            Writer.newline ();            Writer.flush ();       Read server information     String string = Reader.readline ();        SYSTEM.OUT.PRINTLN ("Server:" + string); }    }}

server-side code

/** * Console input information, chat applet * * @author XUYI3 * @ July 18, 2016 @ Morning 10:24:56 * @Server2 * @ Function Description:<br> * @ Spring Breeze ten miles than you * @ remarks */public C Lass Server2 {public static void main (string[] args) throws Exception {//new server-Side ServerSocket object, you must specify a listening port Ser        Versocket ServerSocket = new ServerSocket (9999);        Blocking monitoring ...        SYSTEM.OUT.PRINTLN ("Blocking monitoring");        The listening port creates a new connection socket socket = serversocket.accept ();        Gets the connected input stream InputStream in = Socket.getinputstream () through the socket object;        Get the connected output stream through the socket object OutputStream out = Socket.getoutputstream ();        Use a more convenient buffer wrapper stream to operate BufferedReader reader = new BufferedReader (new InputStreamReader (in));        BufferedWriter writer = new BufferedWriter (new OutputStreamWriter (out));        Console input stream Scanner Scanner = new Scanner (system.in);            while (true) {//Read client information string string = Reader.readline ();            SYSTEM.OUT.PRINTLN ("Client:" + string); Output information to the server SysteM.out.print ("server:");            String line = null;            line = Scanner.nextline ();            Writer.write (line);            The following two steps are very important or there will be problems, the other input stream has been blocked.            Writer.newline ();        Writer.flush (); }    }}
Based on UDP chat program

Client-side code

/** * UDP-based chat program * * @author XUYI3 * @ July 18, 2016 @ Morning 10:52:55 * @UdpClient * @ Function Description:<br> * @ Spring Breeze ten miles than you * @ remarks */public CL The udpclient {public static void main (string[] args) throws Exception {//Packet socket object that can either send a packet or receive a packet (like a postoffice can        The shipment can be received again datagramsocket Datagramsocket = new Datagramsocket (8888);        Scanner Scanner = new Scanner (system.in);            while (true) {//Send data String line = Scanner.nextline (); A packet wraps an object that is used to host data information (similar to a package in a shipping process, where the sending packet usually contains the destination address information to send, the data size, etc.) datagrampacket sendpacket = new Datagrampacket (l            Ine.getbytes (), 0, Line.length (), Inetaddress.getlocalhost (), 8889);            Datagramsocket.send (Sendpacket);            Receive data byte[] tem = new byte[1024];            Receiving packets is usually only required to specify the size of the data to datagrampacket Receivepacket = new Datagrampacket (TEM, tem.length);            Datagramsocket.receive (Receivepacket);            byte[] data = Receivepacket.getdata (); SYSTEM.OUT.PRINTLN ("Server:" + new String (data, 0, data.length)); }    }}

server-side code

/** * UDP-based chat program * * @author XUYI3 * @ July 18, 2016 @ Morning 11:08:49 * @UdpServer * @ Function Description:<br> * @ Spring Breeze ten miles than you * @ remarks */public CL The udpserver {public static void main (string[] args) throws Exception {//Packet socket object that can either send a packet or receive a packet (like a postoffice can        The shipment can be received again datagramsocket Datagramsocket = new Datagramsocket (8889);        Scanner Scanner = new Scanner (system.in);            while (true) {//Receive data byte[] tem = new byte[1024];            Receiving packets is usually only required to specify the size of the data to datagrampacket Receivepacket = new Datagrampacket (TEM, tem.length);            Datagramsocket.receive (Receivepacket);            byte[] data = Receivepacket.getdata ();            SYSTEM.OUT.PRINTLN ("Client:" + new String (data, 0, data.length));            Send data String line = Scanner.nextline (); A packet wraps an object that is used to host data information (similar to a package in a shipment, usually containing the destination address information to send, the size of the data, etc.) Datagrampacket sendpacket = new Datagrampacket (line.g Etbytes (), 0, Line.length (), Inetaddress.getlocalhOST (), 8888);        Datagramsocket.send (Sendpacket); }    }}
TCP-based Network File transfer

Client-side code

/** * 基于TCP实现文件上传和下载功能 *  * @author xuyi3 * @2016年7月18日 @上午11:28:51 * @UploadClient * @功能说明:<br> * @春风十里不如你 * @备注 */public class UploadClient {public static void main(String[] args) throws Exception {        // 客户端新建Socket对象,必须制定主机地址和端口        Socket socket = new Socket("192.168.1.187", 9999);        // 通过Socket对象获得连接的输出流        OutputStream out = socket.getOutputStream();        // 要上传的文件路径        FileInputStream fileInputStream = new FileInputStream(new File("e:/git.png"));        byte[] bytes = new byte[1024];        int len = 0;        while ((len = fileInputStream.read(bytes)) != -1) {            out.write(bytes, 0, len);        }        fileInputStream.close();        out.flush();        out.close();    }}

Server-side code

/** *  * 基于TCP实现文件上传和下载功能 *  * @author xuyi3 * @2016年7月18日 @下午1:27:02 * @UploadServer * @功能说明:<br> * @春风十里不如你 * @备注 */public class UploadServer {public static void main(String[] args) throws Exception {        // 新建服务端ServerSocket对象,必须要指定监听端口        ServerSocket serverSocket = new ServerSocket(9999);        // 阻塞监听...        System.out.println("阻塞监听");        // 监听端口创建一个新的连接        Socket socket = serverSocket.accept();        // 通过Socket对象获得连接的输入流        InputStream in = socket.getInputStream();        // 指定要下载的文件保存路径        FileOutputStream fileOutputStream = new FileOutputStream(new File("e:/gitcopy.png"));        byte[] bytes = new byte[1024];        int len = 0;        while ((len = in.read(bytes)) != -1) {            fileOutputStream.write(bytes, 0, len);        }        fileOutputStream.close();        System.out.println("传输完成");    }}
Multi-Client Chat
多客户端聊天程序,客户端代码不变,服务器端代码需要调整。思路:每连接过来一个客户端就新建一个线程单独给予处理这个客户端,因此要抽取公共代码到线程类里面。

Serverthread Thread Class Code

public class Serverthread implements Runnable {private socket socket;    Public serverthread (socket socket) {this.socket = socket; @Override public void Run () {try {//) get connected input stream via socket object InputStream in = Socket.get            InputStream ();            Get the connected output stream through the socket object OutputStream out = Socket.getoutputstream ();            Use a more convenient buffer wrapper stream to operate BufferedReader reader = new BufferedReader (new InputStreamReader (in));            BufferedWriter writer = new BufferedWriter (new OutputStreamWriter (out));            Console input stream Scanner Scanner = new Scanner (system.in);                while (true) {//Read client information string string = Reader.readline ();                SYSTEM.OUT.PRINTLN ("Client:" + string);                Output information to the server System.out.print ("server:");                String line = null;                line = Scanner.nextline ();                Writer.write (line); The following two steps are very heavyOtherwise it will be a problem, the other input stream has been blocked.                Writer.newline ();            Writer.flush ();        }} catch (Exception e) {e.printstacktrace (); }    }}

Server-side code

/** * 控制台输入信息,聊天小程序<br> * 多客户端聊天,使用多线程为每个客户端新建一个独立线程来使用<br> *  * 客户端代码不用修改,只需要修改服务器端代码即可<br> *  *  * @author xuyi3 * @2016年7月18日 @上午10:24:56 * @Server2 * @功能说明:<br> * @春风十里不如你 * @备注 */public class Server3 {public static void main(String[] args) throws Exception {        // 新建服务端ServerSocket对象,必须要指定监听端口        ServerSocket serverSocket = new ServerSocket(9999);        while (true) {            // 阻塞监听...            System.out.println("阻塞监听");            // 监听端口创建一个新的连接            Socket socket = serverSocket.accept();            new Thread(new ServerThread(socket)).start();        }    }}
Summarize
网络编程的实际用途可能有很多,但是其核心的两种编程模型就是TCP编程模型和UDP编程模型,总体思路都是相同的。
Reference

1, http://www.ibm.com/developerworks/cn/education/linux/l-sock/l-sock.html
2, http://www.cnblogs.com/springcsc/archive/2009/12/03/1616413.html
3, Https://en.wikipedia.org/wiki/Network_socket

Java Network programming

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.