Socket creation
In this chapter you will learn:
- Create Socket from InetAddress
- Create a socket from IP address
- Create a socket with a timeout
- Get IP adress and port for Socket
- Connect to an address
Create Socket from InetAddress
The following code creates an InetAddress
object
first and then creates a Socket
from the InetAddress
object with
a port number.
Create a socket from IP address
The following code create a client with Socket class and points
to IP address 192.2.1.168
port 23
.
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
// j a va 2 s . c o m
public class MainClass {
public static void main(String args[]) {
try {
Socket socket = new Socket("192.2.1.168", 23);
} catch (UnknownHostException e) {
System.out.println(e);
} catch (IOException e2) {
System.out.println(e2);
}
}
}
Create a socket with a timeout
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
/*from j a v a 2 s.co m*/
public class Main {
public static void main(String[] argv) throws Exception {
InetAddress addr = InetAddress.getByName("java.sun.com");
int port = 80;
SocketAddress sockaddr = new InetSocketAddress(addr, port);
Socket sock = new Socket();
int timeoutMs = 2000; // 2 seconds
sock.connect(sockaddr, timeoutMs);
}
}
Get IP adress and port for Socket
After creating the Socket
class we can display Socket
InetAddress, Port, LocalPort and Local address.
import java.net.Socket;
// j av a 2 s . com
public class MainClass {
public static void main(String[] args) throws Exception {
Socket theSocket = new Socket("127.0.0.1", 80);
System.out.println("Connected to " + theSocket.getInetAddress() + " on port "
+ theSocket.getPort() + " from port " + theSocket.getLocalPort() + " of "
+ theSocket.getLocalAddress());
}
}
The code above generates the following result.
Connect to an address
The following code uses a Socket to connect to a domain.
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
/*from java 2s . co m*/
public class Main {
public static void main(String[] argv) throws Exception {
InetAddress addr = InetAddress.getByName("java2s.com");
int port = 80;
SocketAddress sockaddr = new InetSocketAddress(addr, port);
Socket sock = new Socket();
int timeoutMs = 2000; // 2 seconds
sock.connect(sockaddr, timeoutMs);
}
}
Next chapter...
What you will learn in the next chapter:
- How to connect to a host
- How to get InputStream and OutputStream from Socket
- How to wrap DataOutputStream and DataInputStream for Socket
- Read Object from Socket
- Read float number from a Socket
- Compressed socket
Home » Java Tutorial » Socket