Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Modern Programming Language Lesson 5 TCP/IP connection Java stream, filters, java.io TCP/IP communication Simple protocolls [email protected] [email protected] Using streams in Java • Stream: An I/O Stream represents an input source or an output destination. A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays. • The java.io package contains the necessary classes • Life cycle of a stream: – Open Instantiation of the appropriate stream class. – Read/write Using the methods of the stream object. – Close Using the close() method of the stream object. 2 Stream types Main stream classes • Byte streams (descended from InputStream/OutputStream) To perform input and output of 8-bit bytes. • Character streamek (descended from Reader/Writer) The Java platform stores character values using Unicode conventions. Character stream I/O automatically translates this internal format to and from the local character set. In Western locales, the local character set is usually an 8-bit superset of ASCII. 3 Communication using streams • The base class definies the read/write methods • Byte stream (OutputStream) – write(int a) throws IOException – write(byte b[]) throws IOException – write(byte b[], int off, int len) throws IOException • Character stream (Writer) – – – – write(int c) throws IOException write(char c[]) throws IOException write(char c[], int off, int len) throws IOException write(String s) • Clear buffer – Using the flush() method – Closing the stream 4 Read/write using streams • Byte stream (InputStream) – int read() throws IOException – int read(byte c[]) throws IOException – int read(byte c[], int off, int len) throws IOException Result is the number of readed bytes • Character stream (Reader) – int read() throws IOException – int read(char c[]) throws IOException – int read(char c[], int off, int len) throws IOException Állapot Visszatérési érték New data Code of the data item (byte/character) End of data flow -1 No data Stream is waiting 5 Stream example Copy using streams public static void copy(InputStream in, OutputStream out) { try { int b; while (b = in.read() != -1) out.write(b); out.flush(); } catch (IOException e) { System.out.println(e.getMessage()); } } 6 Mapping to physical streams • File handling classes – Character: FileReader/FileWriter – Byte: FileInputReader/FileOutputStream • Available constructors – FileReader(String filename) throws FileNotFoundException – FileReader(File file) throws FileNotFoundException – FileReader(FileDescriptor fd) • Pipe streams – PipedInputStream/PipedOutputStream – PipedReader/PipedWriter • Array streams – pl. CharArrayWriter etc. 7 Filters • Filters are connected to an already existing stream (not directly to the physical medium) • Filters are desendants from streams classes, therefore they can be used as channels (we can connect more than one filter to a stream) A BFilter C Reader Reader Writer Writer BA CAB Filter A B C 8 Using filters • Generally, we define the original stream in the constructor of the filter FileOutputStream fout = new FileOutputStream(”...”); DataOutputStream dos = new DataOutputStream(fout); • We can connect a filter to an other filter too. • In case of connected filters, do not use the stream directly dos.writeFloat(...); • It is enough to close the filter dos.close(); 9 Read/write of Java basic types • Using DataOutputStream filter (connected to a byte stream) – public void writeInt(int v) throws IOException – public void writeFloat(float v) throws IOException – public void writeChar(char v) throws IOException ... • Using DataInputStream filter (connected to a byte stream) – public int readInt() throws IOException – public float readFloat() throws IOException – public char readChar() throws IOException ... 10 Write textual data • Using the PrintWriter filter (connected to a character stream) • Write out data + enter: – public void println(int v) throws IOException – public void println(float v) throws IOException – public void println(String v) throws IOException ... Write out data: – public void print(int v) throws IOException – public void print(float v) throws IOException – public void print(String v) throws IOException ... 11 Reading and parsing textual data • We can use the BufferedReader filter (connected to character streams) – public char read () throws IOException Reads one character – public string readLine() throws IOException Reads a line • We can use the LineNumberReader to count the line numbers (connected to a character stream) – public int getLineNumber() It counts the readed line numbers- 12 Further filters • Convert a byte stream into a character stream InputStreamReader/OutputStreamWriter The constructor gets a byte stream. The object itself is a character stream. • Archiving ZipInputStream/ZipOutputStream GZIPInputStream/GZIPOutputStream • Checked data transfer CheckedInputStream/CheckedOutputStream • Encription CipherInputStream/CipherOutputStream • Object transfer ObjectInputStream/ObjectOutputStream 13 TCP/IP connection • TCP connection is based on sockets. A socket = IP number + port number • The server and the client is the same. The only difference is the connection mode (the client requests the connection, the server receive the request) • There are the same Socket objects in booth side. 14 TCP connection • The java.net package contains – URL handling – TCP connection handling – UDP connection handling (not discussed) • We can start a TCP based connection using the Socket class There are input and output stream in booth side. The server and the client can comminucate via these. Server IP:15.6.8.6 port: 4520 port: 6621 port: 4521 port: 6622 port: 4522 port: 6623 Socket port: 4523 InputStream InputStream OutputStream OutputStream Client IP:12.2.6.5 Socket port: 6624 15 Socket class • Calling the constring initiates the connection – public Socket(String host, int port) throws UnknownHostException, IOException Host format: ”192.168.0.5” or ”www.bmf.hu” Port format: a number between 1 and 65535 • In case of valid connection, we can access the streams using the following methods: – public InputStream getInputStream() throws IOException – public OutputStream getOutputStream() throws IOException • Closing the connection – public void close() throws IOException 16 Client side communication Client example try { Socket s = new Socket("ultra.obuda.kando.hu", 7); InputStream is = s.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); OutputStream os = s.getOutputStream(); PrintWriter pw = new PrintWriter(os); pw.println("ECHO"); pw.flush(); String answer = br.readLine(); System.out.println(answer); s.close(); } catch (Exception e) { System.out.println(e.getMessage()); } 17 ServerSocket class • The ServerSocket constructor needs the following parameters: – public ServerSocket(int port) throws IOException The port parameters is the number of the listening port. If the port number is 0, the server will choose a free port automatically. – public ServerSocket(int port, int backlog) throws IOException the backlog paramters contains the size of the back log. • Closing the ServerSocket object – public void close() throws IOException 18 Listening with ServerSocket • We have to call the following method to put the ServerSocket object into listening phase: – public Socket accept() throws IOException • This will block the program execution, until a new connection request arrives. • If a new connection request apperars, the program will run forward. The result of the accept() method is a Socket object, connected to the client. • After the request handling, we have to call the accept() method agait to listen to the next requets. 19 Server side communication Example: echo protocoll try { ServerSocket ss = new ServerSocket(7); while (true) { Socket s = ss.accept(); InputStream is = s.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); OutputStream os = s.getOutputStream(); PrintWriter bos = new PrintWriter(os); String question = br.readLine(); bos.println(question); bos.flush(); s.close(); } } catch (Exception e) { System.out.println(e.getMessage()); } 20