Memorandum of Rookie Java Java (5)

zhaozj2021-02-16  61

Monday, January 20, 2003

I have added a few Java's basics.

I. Abnormal Java is the same as Delphi, not deliberately avoiding it, but waiting for it to remedy after it. DELPHI's exception handling is simple.

TryExcept // After an abnormality, it is transferred to it.

Similar to this, the basic form of the exception handling of Java is as follows: // Treatment of the abnormal case 1} catch (ExceptionType2 E) {file: // Processing for anomalies 2 THROW (e) // Throw an exception, and the Raise in Delphi is a matter}

To add, for most exceptions, if you want to make a clear throw in the normal running program, Java's compiler requires your exception to be thrown in advance, otherwise It is not allowed to compile. This task is done by throws.

II.Java input / output stream 2.1 Output system.out.print file: // Here OUT is a static method oh system.rr.Print file: // err and OUT are also standard output, as for what is different I don't know the system.rr.println2.2 input System.in.READ () 2.3 files can only be required to have an annotated example. The first is a program that displays basic information of files.

Import java.io. *; // Tell and IO related class class fileInfo {file: // note, main function must be a static method

Public Static Void Main (String Args []) THROWS IOEXCEPTION {file file portocheck; // use file object creation instance if (args.length> 0) {for (int i = 0; i

Public static void info (file f) throws iodception {system.out.println ("name:" f.getname ()); system.out.println ("Path:" f.getPath ()); if (f .exists ()) {system.out.println ("File EXISTS."); System.out.Print ((f.canread ()? "and is readable": ")); // Judgment function, if satisfied Conditions, output the former, otherwise output the latter system.out.print ((f.canwrite ()? "And is write": ""); system.out.print ("."); System.out.println "File IS" f.length () "bytes.");} Else {system.out.println ("File Does NOT EXIST.");}}}

The second example is a small program of a storage telephone information, the user enters the name and phone number, and the program stores it in the phone.NumBers file and implements import java.io. * by FileoutputStream.

class phones {static FileOutputStream fos; public static final int lineLength = 81; public static void main (String args []) throws IOException {byte [] phone = new byte [lineLength]; byte [] name = new byte [lineLength]; INT i; fos = new fileoutputstream ("Phone.NumBers"); while (true) {system.err.println ("Enter a name"); Readline (Name); if ("DONE) ".equalsignorecase (New String (Name, 0, 0, 4)))) {Break;} System.err.Println (" Enter the Phone Number "); Readline (Phone); for (i = 0; Phone [i] ! = 0; i ) {fos.write (phone [i]);} fos.write (','); for (i = 0; Name [i]! = 0; i ) {fos.write (Name [ I]);} fos.write ('/ n');} fos.close ();}

Private static void ready (byte line []) throws = 0, b = 0; while ((i <(linength-1)) && ((b = system.in.read ())! = '/ N ')) {line [i ] = (byte) b;} line [i] = (byte) (0);}}

2.4 The stream is nothing more than two output flows, let us write the input stream, give us a lot of types of input and output streams in the Java.IO package 1.FileInputStream and FileoutPutStream node stream 2. BufferedInputStream and BufferedOutputStream filter flow 3. DataInputStream and DataOutputStream Enhanced Filter Filter 4.pipedinputStream and PipledOutputStream are used for threads

Mastering the concept of streams, you can start Sockets to learn. About the role of Socket, I have already said yesterday.

Now we will create a simple communication program to get a substantive understanding of Socket. This program includes two parts, clientserver. The client issues a request to the server, requiring the read server. The file information. The server will respond to the request, pass the corresponding file information to the client, pass the corresponding file information to the client.

First we create a RemoteFileClient class: import java.io. *; // java.io package provides a tool for reading and writing to TCP sockets, is also the only way to communicate with TCP sockets. *; // java.net package A socket tool is provided.

public class RemoteFileClient {protected String hostIp; protected int hostPort; protected BufferedReader socketReader; // responsible for reading data objects protected PrintWriter socketWriter; // responsible for writing the data object file: // class constructor has two parameters: remote host IP address (HostPort) each. The constructor assigns them to instance variables public remotefileclient (string ahostip, int ahostport) {hostip = ahostip; hostport = ahostport;} public static void main (String [] args ) {} File: // Connect to remote server public void setupConnection () {} file: // Request file information to remote server pUBLIC STRING GETFILE (STRING FILENAMETOGET) {} file: // Disconnect from the remote server PUBLIC VOID TEARDOWNECONNECTION () {}}

First implement Main () public static void main (string [] args) {remoteFileClient RemoteFileClient = New RemoteFileClient ("127.0.0.1", 3000); // For convenience of debugging, we use the local server as a remote server RemoteFileClient.SetupConnection );//connection. You can't use SetupConnection directly, because it is a non-static variable, after you need to create an instance, you can quote the instance, you can see the diary on my first day, very detailed string filecontents = RemoteFileClient.getFile ("remotefile.txt"); / / Read

RemoteFileClient.teardownConnection (); // Disconnected

System.out.println (fileContents); // Output Read Content}

The steps are very clear. Then we look at the connection, read, disconnected 1. Connect public void setupConnection () {Try {socket client = new socket (hostip, hostport); // Create a socket object

OutputStream outToServerStream = client.getOutputStream (); InputStream inFromServerStream = client.getInputStream (); socketReader = new BufferedReader (new InputStreamReader (inFromServerStream)); file: // packed into an InputStream the Socket BufferedReader so that we can read the flow line

SocketWriter = New PrintWriter (OuttoServerstream); file: // Pack the Socket's OutputStream into PrintWrit so that we can send file requests to the server

} catch (unknownhostException e) {system.out.println ("Error Setting Up" Hostip ":" hostport); file: // Create an error to the socket object} catch (IOException) e) {System.out.Println ("Error Setting Up Socket Connection:" E); File: // Abnormal Processing of IO Errors}} 2. Read Public String GetFile (StringBuffer FileLines = New StringBuffer (); // StringBuffer object is also a String object, but is more flexible than it, here is used to store read content.

Try {socketWriter.println (filenametogether); socketWriter.Flush (); // File storage address is output to SocketWrit, then clear the buffer, let this address to send it to the server

String line = null; while (line = socketreader.readline ())! = Null) FileLines.Append (line "/ n"); file: // Since we have sent it to the server, then we all have to wait for a response The program here is waiting for the server to pass the contents of the file we need.} Catch (ioexception e) {system.out.println ("Error Reading from File: FileNameTogether);

Return Filelines.toString (); // Don't forget to convert the content in buffer to string and return}

3. Disconnect Public Void TeardownConnection () {SocketWriter.close (); socketReader.close ();} catch (ooexception e) {system.out.println ("Error Tearing Down Socket Connection: E);} }

TEARDOWNCONNECTION () Method does not close our bufferedReader and PrintWriter created on the INPUTSTREAM and OutputStream created in Socket. This will close the underlying flow of our Socket, so we must capture possible IOException

Ok, you can now summarize the creation step of the client program 1. Instantize the IP port number to connect to the IP port number (if you have any questions). 2. Get the stream on the socket to read and write .3. Package the flow package into the instance of BufferedReader / PrintWrit. 4. Read and write to Socket. Specifically, the file address information is sent to the server on the WRITER, in Reader Read the file information from the server 5. Close the open stream.

Here is the code list of RemoteFileClient

Import java.io. *; import java.net. *;

public class RemoteFileClient {protected BufferedReader socketReader; protected PrintWriter socketWriter; protected String hostIp; protected int hostPort; public RemoteFileClient (String aHostIp, int aHostPort) {hostIp = aHostIp; hostPort = aHostPort;} public String getFile (String fileNameToGet) {StringBuffer fileLines = NEW stringbuffer ();

Try {socketWriter.println (filenametogether); socketwriter.flush ();

String line = null; while ((line = socketreader.readline ())! = Null) FileLines.Append (line "/ n");} catch (ioException e) {system.out.println ("Error Reading from File : " FileNameToget);

return fileLines.toString ();} public static void main (String [] args) {RemoteFileClient remoteFileClient = new RemoteFileClient ( "127.0.0.1", 3000); remoteFileClient.setUpConnection (); String fileContents = remoteFileClient.getFile ( "RemoteFile. TXT "); RemoteFileClient.teardownConnection ();

System.out.println (filecontent);} public void setupconnection () {Try {socket client = new socket (hostip, hostport);

OutputStream outToServerStream = client.getOutputStream (); InputStream inFromServerStream = client.getInputStream (); socketReader = new BufferedReader (new InputStreamReader (inFromServerStream)); socketWriter = new PrintWriter (outToServerStream);

} Catch (UnknownHostException e) {System.out.println ( "Error setting up socket connection: unknown host at" hostIp ":" hostPort);} catch (IOException e) {System.out.println ( "Error setting up socket connection: " e);}} public void tearDownConnection () {try {socketWriter.close (); socketReader.close ();} catch (IOException e) {System.out.println (" Error tearing down socket connection : " E);}}}} Ok, now how to write the server's program. Create a RemoteClientServer class: import java.io. *; import java.net. *;

public class RemoteFileServer {protected int listenPort = 3000; public static void main (String [] args) {} public void acceptConnections () {} public void handleConnection (Socket incomingConnection) {}}

As in the client, first introduce Java.io.io.io.i. Next, give us an instance variable to save the port, and we listen to the entered connection from the port. By default, the port is 3000. Acceptconnections () will allow the client to connect to the server handleConnection () is responsible for interacting with the client Socket to send the content of the file you requested to the client.

First see main ()

Public static void main (string [] args) {remoteFileServer Server = new remoteFileserver (); server.acceptconnections ();} is very simple, because the main function is nothing more than letting the server enters the listening state, so call acceptConnection () directly (). Yes, you must first create an instance of RemoteFileServer () instead of calling.

So how do the server listen to the client's connection through AcceptConnection ()? And if you have heard it, what is it? Let's see public void acceptconnections () {to {serversocket server = new serversocket (listenport); // correspond to the client's socket, on the server side, we need a Serversocket object, the parameters are the port number of the listening to the port number socket incomingConnection = NULL; / / Create a client's Socket variable to receive the socket while (true) {incomingconnection = server.accept (); // calling the serversocket from the client monitor to start listening, handleconnection (incomingConnection) ); File: // Continuously listen until a connection request, then handed over the HandleConnection processing} catch (bindexcect e) {system.out.println ("Unable to bind to port" listen);} catch (ooException E ) {System.out.println ("Unable to instantiate a serversocket on port:" listenport);}} Whenever you create an unable to bind to the specified port (probably because of other controlled this port) ServerSocket, Java code will throw an error. So here we have to capture possible BindException. At the same time, as in the client end, we must capture ioException, which will be thrown when we try to accept the connection on the ServerSocket. You can set the timeout for the ACCEPT () call to avoid the actual long-term wait by calling setsotimeout () to avoid the actual wait. Calling setsotimeout () will throw an IOEXCEPTION after the specified occupancy time

The most critical process is in Handleconnection (), which is already connected to the client's socket, and reads the client's request and responds from the Socket.

public void handleConnection (Socket incomingConnection) {try {OutputStream outputToSocket = incomingConnection.getOutputStream (); InputStream inputFromSocket = incomingConnection.getInputStream ();

File: // First get the stream of streams associated with sockets: //, where OutputTOSocket is to return to the client socket, file: // inputstream is the request from the client, here is the file path, ie "" Remotefile.txt "

BufferedReader StreamReader = New BufferedReader (InputFromSocket);

File: // First to convert the InputStream to BufferedReader

FileReader fileReader = new FileReader (new File (streamReader.readLine ())); file: // read from BufferedReader file path, create a new object FileReaderBufferedReader bufferedFileReader = new BufferedReader (fileReader);

File: // established the bufferedreader object again, this time it reads the content inside the file.

PrintWriter Streamwriter = New PrintWriter (OutputStream);

File: // Pack the Outputtosocket stream of Socket into PrintWrit so that we can send file information to the client

String line = null; while ((line = buffredfilereader.readline ())! = Null) {streamwriter.println (line);} file: // read file information from BufferedFileReader, then output to the client via streamwriter

FileReader.close (); streamwriter.close (); // Note that the two streams of the socket are closed. streamReader.close (); file: // Close all streams after completion

} catch (exception e) {system.out.println ("Error Handling A Client: E);}}

Please pay attention to the order of shutting down the stream after all operations, and the StreamWriter is closed before the StreamReader is closed. This is not accidental. If you turn it off, the client will not get any file information, you can debug a look. This is why? Cause If you close StreamReader before closing streamwriter, you can Streamwriter is written in anything, but no data can pass through the channel (the channel is turned off). But weird, I am not output in the previous streamwriter.println ()? Is it necessary to wait until all streams What can I get to the client's information? I tried to put streamwriter.close (); streamReader.close (); shielded, see if normal communication can be realized, the result is not possible, the program is dead. Maybe because the channel is not It can be made to complete the transmission of communication data only if it can be closed, so that the transmission data is transmitted only if the channel is turned off in some order.

Finally, you will still summarize the steps to create a server-side program 1. Use a port you want to listen to the port that is incoming to the client (such as 3000 in the program) to instantiate a Serversocket (if you have any questions). 2. Circular Call ServerSocket's Accept () to listen to the connection 3. Get the client's Socket flow for read / write operation 4. Package 5. Read and write the client's socket 6. Close the open stream (remember, never be closed Writer is closed before the Reader, complete the communication

Here is the code list of RemoteFileServer

Import java.io. *; import java.net. *;

public class RemoteFileServer {int listenPort; public RemoteFileServer (int aListenPort) {listenPort = aListenPort;} public void acceptConnections () {try {ServerSocket server = new ServerSocket (listenPort); Socket incomingConnection = null; while (true) {incomingConnection = server. Accept (); incomingconnection;}}} catch (bindexception e) {system.out.println ("Unable to bind to port" listen);} catch (ooException e) {system.out.println ("unable to instantiate a ServerSocket on port: " listenPort);}} public void handleConnection (Socket incomingConnection) {try {OutputStream outputToSocket = incomingConnection.getOutputStream (); InputStream inputFromSocket = incomingConnection.getInputStream (); BufferedReader streamReader = new BufferedReader (new InputStreamReader ( Inputfromsocke t));

FileReader FileReader = New FileRead (new file (streamReader.Readline ()));

BufferedReader bufferedFileReader = new BufferedReader (fileReader); PrintWriter streamWriter = new PrintWriter (outputToSocket); String line = null; while (! (Line = bufferedFileReader.readLine ()) = null) {streamWriter.println (line);}

FileReader.close (); streamwriter.close (); streamReader.close ();} catch (exception e) {system.out.println ("Error Handling a client: e);}} public static void main (String [] args) {remoteFileServer Server = New RemoteFileServer (3000); server.acceptconnections ();}} is good, Socket is finally started.

转载请注明原文地址:https://www.9cbs.com/read-27541.html

New Post(0)