Java Language TCP NIO Socket EchoServer&Client Sample Source
JAVA NIO Socket EchoServer
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.Executors;
public class EchoServer implements Runnable {
private InetSocketAddress listenAddress;
public EchoServer(String address, int port) {
listenAddress = new InetSocketAddress(address, port);
}
public void run() {
try (Selector selector = Selector.open()) {
try (ServerSocketChannel serverChannel = ServerSocketChannel.open()) {
serverChannel.configureBlocking(false);
serverChannel.socket().bind(listenAddress);
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
while (selector.select() > 0) {
Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
while (keys.hasNext()) {
SelectionKey key = keys.next();
keys.remove();
if (!key.isValid()) {
continue;
}
if (key.isAcceptable()) {
this.accept(selector, key);
} else if (key.isReadable()) {
this.receive(selector, key);
} else if (key.isWritable()) {
this.send(selector, key);
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void accept(Selector selector, SelectionKey key) {
try {
ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
SocketChannel channel = serverChannel.accept();
channel.configureBlocking(false);
Socket socket = channel.socket();
SocketAddress remoteAddr = socket.getRemoteSocketAddress();
System.out.println("Connected to: " + remoteAddr);
StringBuffer sb = new StringBuffer();
channel.register(selector, SelectionKey.OP_WRITE, sb);
} catch (IOException e) {
e.printStackTrace();
}
}
private void receive(Selector selector, SelectionKey key) {
try {
SocketChannel channel = (SocketChannel) key.channel();
channel.configureBlocking(false);
Socket socket = channel.socket();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int size = channel.read(buffer);
if (size == -1) {
SocketAddress remoteAddr = socket.getRemoteSocketAddress();
System.out.println("Connection closed by client: " + remoteAddr);
channel.close();
socket.close();
key.cancel();
return;
}
byte[] data = new byte[size];
System.arraycopy(buffer.array(), 0, data, 0, size);
StringBuffer sb = (StringBuffer) key.attachment();
sb.append(new String(data));
if (sb.length() > 2 && sb.charAt(sb.length() - 2) == '@' && sb.charAt(sb.length() - 1) == '@') {
String msg = sb.toString();
sb.replace(159,160,"R");
System.out.println(msg);
if ("exit".equals(msg)) {
channel.close();
socket.close();
key.cancel();
return;
}
channel.register(selector, SelectionKey.OP_WRITE, sb);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void send(Selector selector, SelectionKey key) {
try {
SocketChannel channel = (SocketChannel) key.channel();
channel.configureBlocking(false);
StringBuffer sb = (StringBuffer) key.attachment();
String data = sb.toString();
sb.setLength(0);
ByteBuffer buffer = ByteBuffer.wrap(data.getBytes());
channel.write(buffer);
channel.register(selector, SelectionKey.OP_READ, sb);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Executors.newSingleThreadExecutor().execute(new EchoServer("0.0.0.0", Integer.parseInt(args[0])));
}
}
JAVA NIO Socket Client
import java.io.IOException;
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class SocketClient extends Thread {
private static String ipAddress = "";
private static int port = 0;
private static String filePath = "";
private static int thcount = 0;
private static int scount = 0;
private static int totalcount= 1;
public static void main(String[] args) throws IOException {
ipAddress = args[0];
port = Integer.parseInt(args[1]);
filePath = args[2];
thcount = Integer.parseInt(args[3]);
scount = Integer.parseInt(args[4]);
SocketClient c = new SocketClient();
for(int i=0; i<thcount; i++) {
new Thread(c).start();
}
}
public void run() {
try {
InetSocketAddress hostAddress = new InetSocketAddress(ipAddress, port);
SocketChannel client = SocketChannel.open(hostAddress);
System.out.println("Client... connect to " + ipAddress + ":" + port);
String threadName = Thread.currentThread().getName();
long threadNumber = Thread.currentThread().getId();
File f = new File(filePath);
BufferedReader br = new BufferedReader(new FileReader(f));
String message = br.readLine();
br.close();
byte[] bMsg = message.getBytes();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Calendar c1 = Calendar.getInstance();
String strToday = sdf.format(c1.getTime());
ByteBuffer buffer = ByteBuffer.allocate(message.length());
for(int i=0; i<scount; i++) {
String time = String.valueOf(System.nanoTime());
System.arraycopy(strToday.getBytes(), 0, bMsg, 9, 8);
System.arraycopy(time.getBytes(), 0, bMsg, 17, time.length());
buffer.put(bMsg);
buffer.flip();
client.write(buffer);
System.out.println("["+totalcount+"]["+threadNumber+"]send :[" + new String(buffer.array()).substring(0,100) + "...]");
buffer.clear();
client.read(buffer);
System.out.println("["+totalcount+"]["+threadNumber+"]recv :[" + new String(buffer.array()).substring(0,100) + "...]");
buffer.clear();
totalcount++;
}
client.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
HTTP Client
import java.io.*;
import java.net.*;
import java.util.*;
import java.text.SimpleDateFormat;
public class HTTPClient {
public static void post(String address, String postData) throws Exception {
URL url = new URL(address);
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
long sTime = System.currentTimeMillis();
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
long eTime = System.currentTimeMillis();
System.out.println("Connect time : " + (eTime - sTime));
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "text/plain; charset=UTF-8");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.getOutputStream().write(postDataBytes);
System.out.println("send : [" + new String(postDataBytes).substring(0,100) + "...]");
String return_code_from_server = null;
Map hmap = conn.getHeaderFields();
Set hkeys = hmap.keySet();
Iterator it = hkeys.iterator();
while (it.hasNext())
{
String hkey = (String)it.next();
Object value = hmap.get(hkey);
//System.out.println(hkey + ": " + value.toString());
if ((hkey == null) || (hkey.equals("null"))) {
return_code_from_server = value.toString();
//return_code_from_server = "[ HTTP/1.1 200 ]";
}
if ((return_code_from_server != null) && (return_code_from_server.trim().length() > 0))
{
int index = return_code_from_server.indexOf(" ");
int end_index = return_code_from_server.indexOf(" ", index + 1);
String reply_code = return_code_from_server.substring(index + 1, end_index);
}
}
int responseCode = conn.getResponseCode();
StringBuffer responseData = new StringBuffer();
if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
responseData.append(inputLine);
}
in.close();
} else {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
responseData.append(inputLine);
}
in.close();
}
long dTime = System.currentTimeMillis();
System.out.println("Send Receive time : " + (dTime - eTime));
System.out.println("recv : [" + responseData.toString().substring(0,100) + "...]");
}
public static void get(String address) throws Exception {
URL url = new URL(address);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setDoOutput(true);
conn.setUseCaches(false);
System.out.println("send : [" + address + "]");
int responseCode = conn.getResponseCode();
StringBuffer responseData = new StringBuffer();
if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
responseData.append(inputLine);
}
in.close();
} else {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
responseData.append(inputLine);
}
in.close();
}
System.out.println("recv : [" + responseData.toString().substring(0,100) + "...]");
}
public static void main(String argv[]) throws Exception {
BufferedReader reader = new BufferedReader(new FileReader(argv[0]));
String postData = reader.readLine();
reader.close();
int loopCount = Integer.parseInt(argv[1]);
byte[] bData = postData.getBytes();
String address = "http://192.168.253.130:17001/ONLSCOMWE001-initial/EAICall";
SimpleDateFormat dtf = new SimpleDateFormat("yyyyMMdd");
Calendar calendar = Calendar.getInstance();
Date dateObj = calendar.getTime();
String formattedDate = dtf.format(dateObj);
System.arraycopy( formattedDate.getBytes(), 0, bData, 9, 8);
for(int i=0; i<loopCount; i++) {
System.arraycopy( (String.valueOf(System.currentTimeMillis())).getBytes(), 0, bData, 17, 13);
post(address, new String(bData));
}
}
public static String stringToHex(String s) {
String result = "";
for (int i = 0; i < s.length(); i++) {
result += String.format("%02X ", (int) s.charAt(i));
}
return result;
}
}
HTTPS Client
import java.io.*;
import java.net.*;
import javax.net.ssl.*;
import java.security.cert.*;
import java.util.*;
import java.text.SimpleDateFormat;
public class HTTPSClient_auth {
public static void post(String address, String postData) throws Exception {
URL url = new URL(address);
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpsURLConnection conn = null;
long sTime = System.currentTimeMillis();
conn = (HttpsURLConnection)url.openConnection();
conn.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
long eTime = System.currentTimeMillis();
System.out.println("Connect time : " + (eTime - sTime));
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "text/plain; charset=UTF-8");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.getOutputStream().write(postDataBytes);
System.out.println("send : [" + new String(postDataBytes).substring(0,100) + "...]");
String return_code_from_server = null;
Map hmap = conn.getHeaderFields();
Set hkeys = hmap.keySet();
Iterator it = hkeys.iterator();
while (it.hasNext())
{
String hkey = (String)it.next();
Object value = hmap.get(hkey);
if ((hkey == null) || (hkey.equals("null"))) {
return_code_from_server = value.toString();
//return_code_from_server = "[ HTTP/1.1 200 ]";
}
if ((return_code_from_server != null) && (return_code_from_server.trim().length() > 0))
{
int index = return_code_from_server.indexOf(" ");
int end_index = return_code_from_server.indexOf(" ", index + 1);
String reply_code = return_code_from_server.substring(index + 1, end_index);
}
}
int responseCode = conn.getResponseCode();
StringBuffer responseData = new StringBuffer();
if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
responseData.append(inputLine);
}
in.close();
} else {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
responseData.append(inputLine);
}
in.close();
}
long dTime = System.currentTimeMillis();
System.out.println("Send Receive time : " + (dTime - eTime));
System.out.println("recv : [" + responseData.toString().substring(0,100) + "...]");
}
public static void get(String address) throws Exception {
URL url = new URL(address);
HttpsURLConnection conn = null;
long sTime = System.currentTimeMillis();
conn = (HttpsURLConnection)url.openConnection();
conn.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
long eTime = System.currentTimeMillis();
System.out.println("Connect time : " + (eTime - sTime));
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setDoOutput(true);
conn.setUseCaches(false);
System.out.println("send : [" + address + "]");
int responseCode = conn.getResponseCode();
StringBuffer responseData = new StringBuffer();
if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
responseData.append(inputLine);
}
in.close();
} else {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
responseData.append(inputLine);
}
in.close();
}
System.out.println("recv : [" + responseData.toString().substring(0,100) + "...]");
}
public static void main(String argv[]) throws Exception {
BufferedReader reader = new BufferedReader(new FileReader(argv[0]));
String postData = reader.readLine();
reader.close();
int loopCount = Integer.parseInt(argv[1]);
byte[] bData = postData.getBytes();
String address = "https://ism25-ap1:17002/ONLSCOMWE001-initial/EAICall";
SimpleDateFormat dtf = new SimpleDateFormat("yyyyMMdd");
Calendar calendar = Calendar.getInstance();
Date dateObj = calendar.getTime();
String formattedDate = dtf.format(dateObj);
System.arraycopy( formattedDate.getBytes(), 0, bData, 9, 8);
for(int i=0; i<loopCount; i++) {
System.arraycopy( (String.valueOf(System.currentTimeMillis())).getBytes(), 0, bData, 17, 13);
post(address, new String(bData));
}
}
public static String stringToHex(String s) {
String result = "";
for (int i = 0; i < s.length(); i++) {
result += String.format("%02X ", (int) s.charAt(i));
}
return result;
}
}
HTTPS Client(no auth)
import java.io.*;
import java.net.*;
import javax.net.ssl.*;
import java.security.cert.*;
import java.util.*;
import java.text.SimpleDateFormat;
public class HTTPSClient {
public static void post(String address, String postData) throws Exception {
URL url = new URL(address);
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpsURLConnection conn = null;
long sTime = System.currentTimeMillis();
trustAllHttpsCertificates();
conn.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
conn = (HttpsURLConnection)url.openConnection();
long eTime = System.currentTimeMillis();
System.out.println("Connect time : " + (eTime - sTime));
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "text/plain; charset=UTF-8");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.getOutputStream().write(postDataBytes);
System.out.println("send : [" + new String(postDataBytes).substring(0,100) + "...]");
String return_code_from_server = null;
Map hmap = conn.getHeaderFields();
Set hkeys = hmap.keySet();
Iterator it = hkeys.iterator();
while (it.hasNext())
{
String hkey = (String)it.next();
Object value = hmap.get(hkey);
//System.out.println(hkey + ": " + value.toString());
if ((hkey == null) || (hkey.equals("null"))) {
return_code_from_server = value.toString();
//return_code_from_server = "[ HTTP/1.1 200 ]";
}
if ((return_code_from_server != null) && (return_code_from_server.trim().length() > 0))
{
int index = return_code_from_server.indexOf(" ");
int end_index = return_code_from_server.indexOf(" ", index + 1);
String reply_code = return_code_from_server.substring(index + 1, end_index);
}
}
int responseCode = conn.getResponseCode();
StringBuffer responseData = new StringBuffer();
if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
responseData.append(inputLine);
}
in.close();
} else {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
responseData.append(inputLine);
}
in.close();
}
long dTime = System.currentTimeMillis();
System.out.println("Send Receive time : " + (dTime - eTime));
System.out.println("recv : [" + responseData.toString().substring(0,100) + "...]");
}
public static void get(String address) throws Exception {
URL url = new URL(address);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setDoOutput(true);
conn.setUseCaches(false);
System.out.println("send : [" + address + "]");
int responseCode = conn.getResponseCode();
StringBuffer responseData = new StringBuffer();
if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
responseData.append(inputLine);
}
in.close();
} else {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
responseData.append(inputLine);
}
in.close();
}
System.out.println("recv : [" + responseData.toString().substring(0,100) + "...]");
}
public static void main(String argv[]) throws Exception {
BufferedReader reader = new BufferedReader(new FileReader(argv[0]));
String postData = reader.readLine();
reader.close();
int loopCount = Integer.parseInt(argv[1]);
byte[] bData = postData.getBytes();
String address = "https://192.168.253.130:17002/ONLSCOMWE001-initial/EAICall";
SimpleDateFormat dtf = new SimpleDateFormat("yyyyMMdd");
Calendar calendar = Calendar.getInstance();
Date dateObj = calendar.getTime();
String formattedDate = dtf.format(dateObj);
System.arraycopy( formattedDate.getBytes(), 0, bData, 9, 8);
for(int i=0; i<loopCount; i++) {
System.arraycopy( (String.valueOf(System.currentTimeMillis())).getBytes(), 0, bData, 17, 13);
post(address, new String(bData));
}
}
public static String stringToHex(String s) {
String result = "";
for (int i = 0; i < s.length(); i++) {
result += String.format("%02X ", (int) s.charAt(i));
}
return result;
}
private static void trustAllHttpsCertificates() throws Exception {
TrustManager[] trustAllCerts = new TrustManager[1];
TrustManager tm = new miTM();
trustAllCerts[0] = tm;
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
static class miTM implements TrustManager,X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public boolean isServerTrusted(X509Certificate[] certs) {
return true;
}
public boolean isClientTrusted(X509Certificate[] certs) {
return true;
}
public void checkServerTrusted(X509Certificate[] certs, String authType)
throws CertificateException {
return;
}
public void checkClientTrusted(X509Certificate[] certs, String authType)
throws CertificateException {
return;
}
}
}
HTTP Client (JDK11)
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpClient.Version;
import java.net.http.HttpRequest.BodyPublisher;
import java.net.http.HttpRequest.BodyPublishers;
public class HTTPClientJDK11 {
public static void get(String address, String[] headers) throws Exception {
HttpClient client = HttpClient.newBuilder().version(Version.HTTP_1_1).build();
String result = client.sendAsync(
HttpRequest.newBuilder(new URI(address)).GET().headers(headers).build(),
HttpResponse.BodyHandlers.ofString()).thenApply(HttpResponse::body).get();
System.out.println(result);
}
public static void post(String address, String[] headers, BodyPublisher bp) throws Exception {
HttpClient client = HttpClient.newBuilder().version(Version.HTTP_1_1).build();
String result = client.sendAsync(
HttpRequest.newBuilder(new URI(address)).POST(bp).headers(headers).build(),
HttpResponse.BodyHandlers.ofString()).thenApply(HttpResponse::body).get();
System.out.println(result);
}
public static void main(String argv[]) throws Exception {
String address = "http://localhost:29001";
String headers[] = { "Content-Type", "application/json;charset=UTF-8",
"Param1" , "data1",
"Param1", "data2" };
BodyPublisher bp = BodyPublishers.ofString("{ data: \"Data\"}");
post(address, headers, bp);
}
}