------Java Traininglook forward to communicating with you! -------
Java network programming is implemented by the socket class, the network transmission has UDP and TCP protocol, the former does not need the server side, through the packet encapsulation transmission, the data transfer up to 64k, the latter directly establishes the socket stream connection, can transmit very big data
Requirements: Java set up two programs, using the UDP protocol to send a message, the receiving side can receive.
import java.net.*;import java.io.*;p Ublic class udpsend{public void gethost ( string ipaddress) {try{java.net.inetaddress ia = inetaddress.getbyname (ipAddress); String ip = ia.gethostaddress (); String name= ia.gethostname (); SYSTEM.OUT.PRINTLN (IP); SYSTEM.OUT.PRINTLN (name);} catch (exception e) {e.printstacktrace ();}} Public void udpsenddata () throws Exception{DatagramSocket ds = new Datagramsocket (8087);//The content encoded as a byte array, the data is the keyboard input bufferedreader br = new bufferedreader (new inputstreamreader (system.in)); String line = null;while ((Line=br.readline ())!=null) {if ("886". Equals (line)) break;byte [] by = line.getbytes ();//The address sent Inetaddress ia = inetaddress.getbyname (" 192.168.0.149 "),//to encapsulate the sending data in the form of a packet Datagrampacket dp = new datagrampacket (By,0,by.length,ia, 1212);d S.send (DP);} Br.close ();d s.close ();} Public static void main (String [] args) throws exception{udpsend ur = new udpsend (); Ur.udpsenddata ();}} Class udpreceive{public void udpreceivedata () throws exception{datagramsocket ds = new datagramsocket (1212); while (true) {//Received content byte[] by = new byte[1024];/ /Send data encapsulated in packet form Datagrampacket dp = new datagrampacket (by,by.length);d s.receive (DP);//plug-in receiver// The received data decoding string string data = new string (Dp.getdata (), 0,dp.getlength ()); System.out.println (Dp.getaddress (). Gethostaddress () + "::" +data+ "::" +dp.getport ());}} Public static void main (String [] args) throws exception{udpreceive ur = new udpreceive (); Ur.udpreceivedata ();}}
Requirement 2: Implement the Chat program with UDP protocol
Basic idea: Use a main function, set up two threads, which are sending messages and receiving messages, and running two threads at the same time
Requirement 3: Server-side and client communication with TCP protocol, need to ensure that when the client connection, the server knows the IP address of the client, and the server can receive the information sent by the client.
If you have multiple clients connecting to a server, you need to use multi-threading to ensure server-side data security.
import java.util.*;import java.net.*;import java.io.*;p ublic class threaddemo {/ ** * Source: Socket Read Stream * Purpose: Socket output stream **/public void servertcp () throws exception{ Serversocket ss = new serversocket (8001); while (true) {socket s = ss.accept () ;//blocking waits for the connection//Gets the IP address of the connecting client New thread (New serverthread (s)). Start ();}} Public static void main (String[] args) throws Exception{ThreadDemo td = new threaddemo (); Td.servertcp ();}} CLASS CLIENTTCP{PUBLIC VOID CLIENTTCP () throws Exception{Socket s = New socket (); Inetaddress ia = inetaddress.getbyname ("192.168.0.149"); S.connect (new Inetsocketaddress (ia,8001)); while (true) {Bufferedreader br = new bufferedreader (new InputStreamReader (system.in)); Outputstream os = s.getoutputstream (); printwriter pw = New printwriter (os,true);//Auto-refresh String line = br.readline ();p w.println (line), if ("over". Equals (line)) break;}} Public static void main (String[] args) throws exception{clienttcp td =  NEW CLIENTTCP (); TD. Clienttcp ();}} class serverthread implements runnable{socket s; Serverthread (socket s) { this.s=s;} public void run () {try{string ip = s.getinetaddress (). getHostAddress (); System.out.println (ip+ " Client connection ..."); while (true) {Inputstream is = s.getinputstream (); Bufferedreader br = new bufferedreader (New inputstreamreader (IS)); String line = br.readline (); if ("over". Equals line) break; System.out.println (line);} System.out.println (ip+ " client disconnects ..."); catch (exception e) {new runtimeexception ("Accept failed");} }}
Because the TCP protocol client and server side are using the blocking method, when the program does not stop, we start from the server or client blocking method to solve the problem, this is the most straightforward solution.
Requirement 4: Use the TCP protocol to upload files to the server in a multi-threaded manner
import java.util.*;import java.net.*;import java.io.*;p ublic class tcpdemo {/** * Source: Socket Read Stream * Purpose: Socket output stream **/public static void main (String[] args) Throws exception{serversocket ss = new serversocket (8001); while (true) {Socket s = ss.accept (); New thread (New mythread (s)). Start ();}} Class clienttcp{public void sendfile (String[] args) throws exception{socket s = new socket ("192.168.0.149", 8001); File f = new file (Args[0]); Inputstream is = new fileinputstream (f); O Utputstream os = s.getoutputstream (); int len = 0;byte[] by = new byte[1024];while ((Len=is.read (by))!=-1) {os.write (By,0,len);} S.shutdownoutput (); Byte[] by1 = new byte[1024];int arr = s.getinputstream () . read (by1); System.out.println (New striNg (By1,0,arr)); S.close ();} Public static void main (String[] args) throws exception{clienttcp td = new clienttcp (); Td.sendfile (args);}} class mythread implements runnable{socket s; MyThread (socket s) {this.s=s;} Public void run () {try{//Gets the IP address of the connecting client string ip = s.getinetaddress (). Gethostaddress (); System.out.println (ip+ " Client connection ..."); Inputstream is = s.getinputstream (); int count = 1; File f1 = new file ("d:\\" +ip+ ". jpg"), while (F1.exists ()) f1 = new file ("d:\\" +ip+ "_ (" + (count++) + "). jpg"); Outputstream os = new fileoutputstream (F1); byte[] by = new byte[1024];int len = 0;while ((Len=is.read (by))!=-1) {os.write (By,0,len);} Printwriter out = new printwriter (S.getoutputstream (), true); Out.println ("Upload succeeded");} catch (Exception e) {}}}
Black Horse programmer __tcp and UDP summary