Constructor | Description |
---|---|
Socket() | Creates an unconnected socket, with the system-default type of SocketImpl. |
public Socket(InetAddress address, int port) | Creates a stream socket with specified IP address to the specified port number. |
public Socket(InetAddress host, int port, boolean stream) | Uses the DatagramSocket. |
public Socket(InetAddress address, int port, InetAddress localAddr, int local port) | Creates a connection with specified remote address and remote port. |
public Socket(Proxy, proxy) | Creates a connectionless socket specifying the type of proxy. |
protected Socket(SocketImpl impl) | Creates a connectionless Socket with a user-specified SocketImpl. |
Constructor | Description |
---|---|
ServerSocket() | Creates an unbound server socket. |
ServerSocket(int port) | Creates a server socket, bound to the specified port. |
ServerSocket(int port, int backlog) | Creates a server socket, bound to the specified port, with specified local port. |
ServerSocket(int port, int backlog, inetAddress bindAddrs) | Creates a server socket, bound to specified port, listen backlog, and IP address. |
import java.io.*;
import java.net.*;
public class SerSocket
{
public static void main(String args[])
{
int port=8080;
try
{
ServerSocket ss = new ServerSocket(port);
System.out.println("Server initialized on port: " + port);
ss.getLocalPort();
ss.getInetAddress();
{
while(true)
ss.accept();
}
}
catch (SocketException e)
{
System.out.println("Socket error");
}
catch ( IOException e)
{
System.out.println("An I/O Exception Occurred!");
}
}
}
// ClientDemo.java
import java.io.InputStream;
import java.io.DataInputStream;
import java.net.Socket;
public class ClientDemo
{
public static void main(String args[])
{
try
{
Socket s = new Socket("localhost", 7777);
InputStream in = s.getInputStream();
DataInputStream dis = new DataInputStream(in);
String msg = dis.readLine();
System.out.println("Server message is: "+ msg);
dis.close();
s.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
// ServerDemo.java
import java.io.OutputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.net.ServerSocket;
public class ServerDemo
{
public static void main(String args[])
{
try
{
ServerSocket ss = new ServerSocket(7777);
System.out.println("Server is ready.");
Socket s = ss.accept();
System.out.println("COnnection created.");
System.out.println("Sent message to client.");
OutputStream out = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
dos.writeBytes("Welcome");
dos.close();
s.close();
ss.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}