TCP Server
package com.socket;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class Server {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ServerSocket server = new ServerSocket(9999);
Socket socket = null;
while(true){
socket = server.accept();
OutputStream out = socket.getOutputStream();
DataOutputStream dataOutputStream = new DataOutputStream(out);
dataOutputStream.writeUTF("Hi client" + new Date().toString());
dataOutputStream.close();
out.close();
socket.close();
}
}
}
TCP Client
package com.socket;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
/**
* @param args
* @throws IOException client
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException {
// TODO Auto-generated method stub
Socket client = new Socket("localhost", 9999);
InputStream in = client.getInputStream();
DataInputStream dis = new DataInputStream(in);
System.out.println(dis.readUTF());
in.close();
dis.close();
client.close();
}
}
UDP Server
package com.socket;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDPServer {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
DatagramSocket socket = new DatagramSocket(8888);
byte[] buf = new byte[1000];
DatagramPacket p = new DatagramPacket(buf, buf.length);
while(true){
socket.receive(p);
DatagramPacket resPacket = new DatagramPacket(p.getData(), p.getData().length, p.getAddress(), p.getPort());
socket.send(resPacket);
}
}
}
UDP Client
package com.socket;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class UDPClient {
/**
* @param args
* @throws IOException
* @throws SocketException
*/
public static void main(String[] args) throws SocketException, IOException {
// TODO Auto-generated method stub
DatagramSocket socket = new DatagramSocket();
String s = "Hello UDP11";
DatagramPacket p = new DatagramPacket(s.getBytes(), s.getBytes().length,
InetAddress.getByName("localhost"), 8888);
socket.send(p);
byte[] buffer = new byte[1000];
DatagramPacket rp = new DatagramPacket(buffer, buffer.length);
socket.receive(rp);
System.out.println(new String(rp.getData()));
socket.close();
}
}