+ All Categories
Home > Technology > Network programming1

Network programming1

Date post: 30-Jul-2015
Category:
Upload: soham-sengupta
View: 311 times
Download: 2 times
Share this document with a friend
10
Network Programming with Java
Transcript

Network Programming with Java

public static void main(String[] args) throws UnknownHostException {InetAddress localAddress = InetAddress.getLocalHost();System.out.println(localAddress.getHostAddress());

}

public static void main(String[] args) throws UnknownHostException {InetAddress googleAddress = InetAddress.getByName("www.google.com");System.out.println(googleAddress.getHostAddress());}

TCP/IP Server: That(a program or a process) listens to a TCP port.Client: What (a program or a process) initiates the connection Server is represented by java.net.ServerSocketClient is represented by java.net.Socketint portNumber = 7896; // TCP port NumberServerSocket server = new ServerSocket(portNumber);// listen on portSocket socket = server.accept(); // Blocks until connection made

String destIP = "172.17.20.123"; // Target Host IPv4 Addressint portNumber = 7896; // TCP port NumberSocket socket = new Socket(destIP, portNumber);// connect

Stay & while connected…

Server Client

Wait for connection

Server’s Output/ Client’s Input

Client’s Output/ Server’s Input

Java I/O

Some important OutputStream child: DataOutputStreamFileOutputStreamByteArrayOutputStream

Java I/O

Some important InputStream child:DataInputStreamFileInputStreamByteArrayInputStream

Read an input integer Example

File Handling

if(false==dir.exists() || false==dir.isDirectory()){dir.mkdirs();}

File Handling

5. Open an OutputStream to the file:

6. Write the raw bytes to the OutputStream, flush and close it

Write to a File : Second approach

DataOutputStream provides a wrapper over an OutputStream towrite primitive data types, not just byte[]

Read from a FileRead byte-by-byte

Read Bytes chunk-wise : Faster approach


Recommended