Java Learning Path Network programming-exercises __ Programming

Source: Internet
Author: User
Tags flush readline
Package com.atguigu.javase.net;
Import Java.io.BufferedReader;
Import Java.io.BufferedWriter;
Import Java.io.InputStreamReader;
Import Java.io.OutputStreamWriter;
Import Java.net.ServerSocket;

Import Java.net.Socket; The client sends a string to the server, and the server receives a reply message to the client confirming that public class Nettest {@Test public void server () {ServerSocket server = null;
		
		/Service SOCKET SOCKET SOCKET1 = NULL; InputStream is = null;  Network input stream InputStreamReader ISR = null; Convert stream BufferedReader bufreader = null; Buffer stream OutputStream OS = null; Network output stream OutputStreamWriter OSW = null; Convert stream BufferedWriter bufwriter = null; Buffer stream try {server = new ServerSocket (9999);//server bound on port number 9999 Socket1 = Server.accept ();//Accept method causes program blocking, waiting for guest
			
			User-side connection request, once accepted, returns a socket object System.out.println (SOCKET1);
			is = Socket1.getinputstream ();
			ISR = new InputStreamReader (IS);
			
			Bufreader = new BufferedReader (ISR);
			String line = Bufreader.readline ();
			
			System.out.println (line); OS = socket1.getoutPutstream ();
			OSW = new OutputStreamWriter (OS);
			Bufwriter = new BufferedWriter (OSW);
			Bufwriter.write ("I have received your message, please rest assured!!");
			Bufwriter.newline ();
		Bufwriter.flush ();
		catch (Exception e) {e.printstacktrace ();
			Finally {try {bufreader.close ();
			The catch (Exception E2) {} try {bufwriter.close ();
			The catch (Exception E2) {} try {socket1.close ();
			The catch (Exception E2) {} try {server.close ();
		The catch (Exception E2) {}}} @Test public void Client () {Socket socket2 = null;
		OutputStream OS = null;
		OutputStreamWriter OSW = null;
		
		BufferedWriter bufwriter = null;
		InputStream is = null;
		InputStreamReader ISR = null;
		
		BufferedReader bufreader = null; try {Socket2 = new socket ("127.0.0.1", 9999)//The process of creating a Socket object is the process of initiating the request, and the information required to connect to the server is the host (IP) and Port System.out.prin
			TLN (Socket2); OS = Socket2.getoutputstream (); 
			Gets the output stream object OSW = new OutputStreamWriter (OS); Bufwriter = new BufferedwRiter (OSW);
			Bufwriter.write ("Hello server, I am client!!");
			Bufwriter.newline (); Bufwriter.flush ();
			The Data brush network line is = Socket2.getinputstream ();
			ISR = new InputStreamReader (IS);
			Bufreader = new BufferedReader (ISR);
			String line = Bufreader.readline ();
			
		System.out.println (line);
		catch (Exception e) {e.printstacktrace ();
			Finally {try {bufwriter.close ();
			The catch (Exception E2) {} try {bufreader.close ();
			The catch (Exception E2) {} try {socket2.close (); The catch (Exception E2) {}} class Exerserver {//server proactively sends a UTF8 string to the client that the client receives to reverse process and return to server public s
		tatic void Main (string[] args) {ServerSocket server = null;
		Socket socket1 = null;
		BufferedWriter bufwriter = null;
		BufferedReader bufreader = null; try {server = new ServerSocket (8888);//Once the object is successfully created, flag this program and port 8888 bind while (true) {System.out.println (server is 8888 port
				Monitor ... ");
					try {socket1 = server.accept (); Bufwriter= new BufferedWriter (New OutputStreamWriter (Socket1.getoutputstream (), "UTF8"));
					
					Bufreader = new BufferedReader (New InputStreamReader (Socket1.getinputstream (), "UTF8"));
					Bufwriter.write ("Write a string, send to the client, I am the server");
					Bufwriter.newline ();
					
					Bufwriter.flush ();
					String line = Bufreader.readline ();
				System.out.println (line);
					catch (Exception e) {} finally {try {bufreader.close ();
					The catch (Exception E2) {} try {bufwriter.close ();
					The catch (Exception E2) {} try {socket1.close ();
		catch (Exception E2) {}} \ catch (Exception e) {e.printstacktrace ();
			Finally {try {server.close (); Class Exerclient {///client received this string in reverse processing and returned to server public static void main (string[] A (Exception E2) {}}}
		RGS) {Socket Socket2 = null;
		BufferedReader bufreader = null;
		BufferedWriter bufwriter = null; try {Socket2 = new Socket ("LocalhosT ", 8888);
			Bufreader = new BufferedReader (New InputStreamReader (Socket2.getinputstream (), "UTF8"));
			Bufwriter = new BufferedWriter (New OutputStreamWriter (Socket2.getoutputstream (), "UTF8"));
			String line = Bufreader.readline ();
			System.out.println (line);
			line = new StringBuilder (line). reverse (). toString ();
			Bufwriter.write (line);
			Bufwriter.newline ();
		Bufwriter.flush ();
		catch (Exception e) {e.printstacktrace ();
			Finally {try {bufreader.close ();
			The catch (Exception E2) {} try {socket2.close ();

The catch (Exception E2) {}}}} package com.atguigu.javase.net;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import Java.net.ServerSocket;

Import Java.net.Socket;  Class TestServer2 {//Receive the file sent from the client and save locally, after processing, give the client feedback public static void main (string[] args) {ServerSocket Server =
		Null
		Socket socket1 = null; InputStream is = null; Network input stream FileoUtputstream fos = null; File output stream OutputStream OS = null;
			Network output stream try {server = new ServerSocket (6666);
			Socket1 = Server.accept ();
			is = Socket1.getinputstream ();
			
			OS = Socket1.getoutputstream ();
			FOS = new FileOutputStream ("girl2.jpg");
			byte[] buf = new byte[8192]; int realcount = Is.read (BUF); Read data from the network input stream while (Realcount!=-1) {fos.write (buf, 0, Realcount);//write the read data to the local file Realcount = Is.read (buf ); The other end of the network closes the output return-1} os.write ("Received". GetBytes ());
		Feedback a string Os.flush () through the network output stream;
		catch (Exception e) {e.printstacktrace ();
			Finally {try {fos.close ();
			The catch (Exception E2) {} try {is.close ();
			The catch (Exception E2) {} try {os.close ();
			The catch (Exception E2) {} try {socket1.close ();
			The catch (Exception E2) {} try {server.close (); The catch (Exception E2) {}} class TestClient2 {//Send a file to the server side, then receive server feedback public static void main (Strin G[] ARGS) {Socket Socket2 = null; FileInputStream FIS = null; Read the local file input stream outputstream OS = null; Send file, network output stream inputstream is = null;
			Network input stream try {String host = "localhost";
			int port = 6666;
			Socket2 = new Socket (host, Port);
			OS = Socket2.getoutputstream ();
			
			is = Socket2.getinputstream ();
			FIS = new FileInputStream ("girl.jpg");
			byte[] buf = new byte[8192]; int realcount = Fis.read (BUF); Get the data from the file input stream while (Realcount!=-1) {//1) process Os.write (buf, 0, Realcount);
			Write the read data directly into the network output stream//2) Continue Realcount = Fis.read (BUF); } socket2.shutdownoutput (); Turn off the output stream and send a termination signal to the other end of the network Realcount = Is.read (BUF);
			Getting feedback from the network input stream is a string, so you need to decode string line = new String (buf, 0, Realcount);
		System.out.println (line);
		catch (Exception e) {e.printstacktrace ();
			Finally {try {fis.close ();
			The catch (Exception E2) {} try {os.close ();
			The catch (Exception E2) {} try {is.close (); catch (excePtion E2) {} try {socket2.close ();

The catch (Exception E2) {}}}///Send a string using UDP package com.atguigu.javase.net;
Import Java.net.DatagramPacket;
Import Java.net.DatagramSocket;

Import java.net.InetAddress;

Import Org.junit.Test;
		public class NetTest3 {@Test public void Udpsender () throws Exception {datagramsocket ds = new Datagramsocket ();
		byte[] data = "Come to a date, is a string". GetBytes ();
		Datagrampacket DP = new Datagrampacket (data, 0, Data.length, inetaddress.getbyname ("127.0.0.1"), 10000); Ds.send (DP);
	Sending the data packages to the hardware ds.close ();  @Test public void Udpreceiver () throws Exception {datagramsocket ds = new Datagramsocket (10000);//bind Port byte[]
		BUF = new byte[8192];
		Datagrampacket DP = new Datagrampacket (buf, buf.length); Receive data ds.receive (DP);
		The received data is saved in the Datagrampacket object string string = new String (buf, 0, Dp.getlength ());
		System.out.println (string);
	Ds.close ();

}} package com.atguigu.javase.net; Import Java.io.BuffeRedreader;
Import Java.io.BufferedWriter;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.io.OutputStream;
Import Java.io.OutputStreamWriter;
Import java.net.InetAddress;
Import Java.net.ServerSocket;
Import Java.net.Socket;

Import java.net.UnknownHostException;
Import Org.junit.Test; Create a server can receive information from the client and print out on the console,////client receive keyboard input string, and send to server, where multiple threads need to be created to prevent multiple clients from connecting to the server when one of the servers occurs//fails, the server can still run class
	
	Tcpservice implements Runnable {private Socket socket1;
	Public Tcpservice (Socket socket1) {this.socket1 = Socket1;
		@Override public void Run () {BufferedReader bufreader = null;
			try {bufreader = new BufferedReader (New InputStreamReader (Socket1.getinputstream ()));
			String line = Bufreader.readline ();
				While [line!= null] {System.out.println (line);
			line = Bufreader.readline ();
		} catch (Exception e) {e.printstacktrace ();
			Finally {try {bufreader.close (); catch (Exception E2){} try {socket1.close (); ' Catch (Exception E2) {}}} ' class TestServer1 {public static void main (string[] args) {ServerSocket s
		erver = null;
			try {server = new ServerSocket (7777);
				while (true) {System.out.println ("Server listens on port 7777 ...");
				Socket Socket1 = server.accept ();
			New Thread (New Tcpservice (Socket1)). Start ();
		} catch (Exception e) {e.printstacktrace ();
			Finally {try {server.close ();
			catch (IOException e) {e.printstacktrace ();
		Class TestClient1 {public static void main (string[] args) {Socket socket2 = null;
		BufferedReader bufreader = null;
		
		BufferedWriter bufwriter = null;
			try {Socket2 = new Socket ("localhost", 7777);
			Bufreader = new BufferedReader (new InputStreamReader (system.in));
			Bufwriter = new BufferedWriter (New OutputStreamWriter (Socket2.getoutputstream ()));
			String line = Bufreader.readline ();
				While [line!= null] {bufwriter.write (line);Bufwriter.newline ();
				
				Bufwriter.flush ();
			line = Bufreader.readline ();
		} catch (Exception e) {e.printstacktrace ();
			Finally {try {bufreader.close ();
			The catch (Exception E2) {} try {bufwriter.close ();
			The catch (Exception E2) {} try {socket2.close ();

The catch (Exception E2) {}}}} package com.atguigu.javase.net;
Import Java.io.BufferedReader;
Import Java.io.BufferedWriter;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.OutputStreamWriter;
Import Java.net.ServerSocket;

Import Java.net.Socket; 
	
	* * Create servers and clients so that servers and clients can type each other to communicate/class TCP implements Runnable {//Receive information from the network, and on the console, print out private socket socket;
	Public TCP (socket socket) {this.socket = socket;
		@Override public void Run () {BufferedReader bufreader = null;
			try {bufreader = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));
			String line = Bufreader.readline (); while (line!= NULL) {System.out.println (line);
			line = Bufreader.readline ();
		} catch (Exception e) {e.printstacktrace ();
			Finally {try {bufreader.close ();
			The catch (Exception E2) {} try {socket1.close (); ' Catch (Exception E2) {}}} ' class TestServer3 {public static void main (string[] args) {//Create client Server
		Socket server = null;
		Socket socket1 = null; BufferedReader br = null; Keyboard input stream BufferedReader BR1 = null; Network input stream bufferedwriter bw =null;
			Network output stream try {server = new ServerSocket (8888);
			SYSTEM.OUT.PRINTLN ("Server is listening on port 8888 ...");
			
			Socket1 = Server.accept ();
			br = new BufferedReader (new InputStreamReader (system.in));
			BW = new BufferedWriter (New OutputStreamWriter (Socket1.getoutputstream ()));
			BR1 = new BufferedReader (New InputStreamReader (Socket1.getinputstream ()));
			
			Create the thread and run new thread (new TCP (Socket1)). Start ();
			The string entered by the keyboard and passed to the client string line = Br.readline (); while (line!= null) {
				Bw.write (line);
				Bw.newline ();
				
				Bw.flush ();
			line = Br.readline ();
		} catch (Exception e) {e.printstacktrace ();
			Finally {try {br1.close ();
			catch (IOException e) {} try {bw.close ();
			catch (IOException e) {} try {socket1.close ();
			catch (IOException e) {} try {server.close ();  ' Catch (IOException e) {}}} ' class TestClient3 {public static void main (string[] args) {Socket Socket2
		= NULL; BufferedReader br = null; Network input stream BufferedReader BR2 = null; Keyboard input stream BufferedWriter bw = null;
			Network output stream try {Socket2 = new Socket ("127.0.0.1", 8888);
			br = new BufferedReader (New InputStreamReader (Socket2.getinputstream ()));
			BR2 = new BufferedReader (new InputStreamReader (system.in));
			BW = new BufferedWriter (New OutputStreamWriter (Socket2.getoutputstream ()));
			
			Create a thread and run new thread (new TCP (Socket2)). Start (); Receives the keyboard incoming string and sends it to the server-side string line2 = Br2.readline ();
				while (line2!= null) {bw.write (line2);
				Bw.newline ();
				Bw.flush ();
			Line2 = Br2.readline ();
		} catch (Exception e) {e.printstacktrace ();
			Finally {try {bw.close ();
			catch (IOException e) {} try {br2.close ();
			catch (IOException e) {} try {br.close ();
			catch (IOException e) {} try {socket2.close ();
 The catch (IOException e) {}}}}

Related Article

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.