Java Socket how to simulate disconection from server - java

I have a Java program with a client and server sockets, there I want to test that an exception is raised after the server is down.
This is the server:
public class SocketServer implements Runnable {
private bool serverRuns = false;
private int timeout = 10000;
private DataInputStream in;
private DataOutputStream out;
private Socket client;
private ServerSocket server;
private String message = "Ok";
private waitForInstruction = true;
public SocketServer() throws IOException {
ServerSocket server = new ServerSocket(tcpPort,0,ipAdress);
serverRuns = true;
server.setSoTimeout(timeout)
}
private void waitForClient() {
try {
client = server.accept();
client.setSoTimeout(timeout);
in = new DataInputStream(client.getInputStream());
out = new DataOutputStream(client.getOutputStream());
} catch (IOException e) {
fail("I/O Error " + e.getMessage());
}
}
public void run() {
waitForClient();
while (serverRuns) {
if (clientSocket.isClosed()) {
waitForClient();
}
try {
while (waitForInstruction == false) {
// Read input message
String inputStreamString = "";
while (in.available() > 0) {
int c = in.read();
inputStreamString += (char) c;
}
out.write(message.getBytes());
System.out.println("Sent bytes: " + out.size());
setWaitForInstruction(true);
}
} catch (IOException E) {
fail("I/O Error " + E.getMessage());
}
}
}
public void closeServerSocket() {
try {
serverRuns = false;
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
void setWaitForInstruction(boolean waitForInstruction) {
this.waitForInstruction = waitForInstruction;
}
public void startServerSocket() {
serverRuns = true;
}
}
This is the client:
public class SocketClient extends Socket {
private InetAddress address;
private short tcpPort;
private DataInputStream in;
private DataOutputStream out;
private static final int timeOut = 10000;
public SocketClient(InetAddress address, short tcpPort) {
this.tcpPort = tcpPort;
this.address = address;
}
public void connect() throws IOException, SocketTimeoutException {
super.connect(new InetSocketAddress(address, tcpPort), timeOut);
}
public void doStuff() throws IOException {
String request = "Ok?";
String InputStreamString = "";
super.setSoTimeout(timeOut);
this.setSoTimeout(timeOut);
out = new DataOutputStream(super.getOutputStream());
in = new DataInputStream(super.getInputStream());
out.writeBytes(requestString);
int c;
do {
if (in.available() > 0) {
c = in.read();
InputStreamString += (char) c;
}
} while (!InputStreamString.equals("Ok"));
System.out.println(InputStreamString);
}
}
I start the server socket thread with:
#BeforeClass
public static void startSocket() throws IOException {
testServer = new SocketServer();
monitor = new Thread(testServer);
monitor.setName("Test Server Thread");
monitor.setDaemon(true);
monitor.start();
}
And the JUnit test is this:
#Before
public void createSocket() throws Exception {
ipAdress = InetAddress.getLocalHost();
SystemConfig.setLoggerConfigFilePath("LoggerConfig.xml");
socketClient = new SocketClient(ipAdress, 5000);
}
#Test
public void checkServerisDown() {
try {
socketClient.connect();
} catch (IOException e) {
fail("IO Error");
}
testServer.closeServerSocket();
monitor.interrupt();
try {
testServer = new SocketServer();
monitor = new Thread(testServer);
monitor.setName(" Test Server Thread");
monitor.setDaemon(true);
// monitor.start();
testServer.startServerSocket();
testServer.setWaitForInstruction(false);
System.out.print("Test (1/1) CHECK SERVER IS DOWN.....\n");
socketClient.doStuff();
System.out.println("NOT OK!");
} catch (IOException e) {
fail("IO Error " + e.getMessage() + " OK");
}
try {
drEstimControlInterface.close();
testServer.getSocket().close();
} catch (IOException e) {
fail("IO Error");
}
}
#AfterClass
public static void closeSocket() throws IOException {
testServer.closeSocket();
}
However the test is not performing as I intended, I thought that this should return an IOException since the server socket has been closed and the thread has been interrupted, but the client socket still gets the answer from the server socket and prints the "NOT OK!". Could anybody tell me why?

You have to close not only ServerSocket but client socket with streams too.
public void closeServerSocket() {
try {
serverRuns = false;
serverSocket.close();
in.close();
out.close();
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Related

StreamCorruptedException: invalid type code: 64

I'm trying to send Message object from Server module to Client module. Unfortunately it throw java.io.StreamCorruptedException: invalid type code: 64 error. Does anyone know what is the problem with code below?
Client class from Server module
private boolean needToRun;
public final Socket socket;
private OutputStream outputStream;
private InputStream inputStream;
private ObjectOutputStream objOut;
private ObjectInputStream objIn;
public Client(Socket socket) {
this.needToRun = true;
this.socket = socket;
try {
this.outputStream = socket.getOutputStream();
this.inputStream = socket.getInputStream();
this.objOut = new ObjectOutputStream(outputStream);
this.objIn = new ObjectInputStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
run();
}
public void send(Message msg) {
try {
objOut.writeObject(msg);
objOut.flush();
objOut.reset();
} catch (Exception ex){
ex.printStackTrace();
}
}
public void close() {
needToRun = false;
}
public void run() {
new Thread(() -> {
while(needToRun) {
try {
int amount = inputStream.available();
if (amount != 0) {
Message msg = (Message) objIn.readObject();
receivedContent(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
public void receivedContent(Message msg) {
for (Client connection : Server.clients) {
connection.send(msg);
}
}
the Client class from Client module looks the same but receivedContent looks like this:
public void receivedContent(Message msg) {
String errorName = msg.content().trim();
MainPane.addLabel(errorName);
}
and last one Server class, which accepts socket connections:
while (true) {
System.out.println("running");
try {
System.out.println("Waiting for client...");
Socket socket = serverSocket.accept();
clients.add(new Client(socket));
} catch (Exception e) {
if (!serverSocket.isClosed()) {
stopServer();
}
break;
}
}

Incorrect user delete from list on sever side

I have a small primitive server for studying, and client side.
Here I have piece of my server code:
public class Connector implements Runnable, SocketListener {
private Socket socket;
private ServerSocket serverSocket;
private List<ServerSideClient> clients = new LinkedList<>();
private boolean triger;
public Connector(ServerSocket serverSocket) {
this.serverSocket = serverSocket;
}
#Override
public void run() {
while (true) {
try {
System.out.println("Waiting for clients..");
triger = true;
socket = serverSocket.accept();
System.out.println("Client connected");
ServerSideClient client = createClient();
client.setConnection(true);
client.startListeningClient();
clients.add(client);
new Thread(() -> {
socketIsClosed(client);
}).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private ServerSideClient createClient() {
return new ServerSideClient(socket);
}
#Override
public synchronized void socketIsClosed(ServerSideClient client) {
while (triger == true) {
if (client.isConnected() == false) {
triger = false;
clients.remove(client);
System.out.println("Client was removed " + clients.size());
}
}
}
}
Here we wait for new Client, then create client instance and add it to LinkedList. In instance on server side we waiting information from client and sending answer on separated thread. But when client closes connection with server, socketIsClosed() method should to delete current client reference from collection. But when client is disconnected I haven't even Logout System.out.println("Client was removed " + clients.size()); from socketIsClosed(ServerSideClient client) method.
Client Code:
public class Client {
private final String HOST = "localhost";
private final int PORT = 1022;
private InputStream inputStream;
private OutputStream outputStream;
private BufferedReader bufferedReader;
private Socket socket;
private boolean connection;
public Client() throws IOException {
socket = new Socket();
socket.connect(new InetSocketAddress(HOST, PORT));
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
bufferedReader = new BufferedReader(new InputStreamReader(System.in));
}
public static void main(String[] args) {
Client client = null;
try {
client = new Client();
client.work();
} catch (IOException e) {
e.printStackTrace();
}
}
private void work() {
connection = true;
listenForConsoleInput();
receiveAnswerFromServer();
}
private void listenForConsoleInput() {
new Thread(() -> {
while (connection == true) {
String requset = null;
try {
requset = bufferedReader.readLine();
if (requset.equals(".")) {
closeConnection();
return;
} else {
sendRequest(requset);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private void sendRequest(String request) {
try {
outputStream.write(request.getBytes());
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void receiveAnswerFromServer() {
new Thread(() -> {
while (connection == true) {
byte[] data = new byte[32 * 1024];
try {
int numberOfBytes = inputStream.read(data);
System.out.println("Server>> " + new String(data, 0, numberOfBytes));
} catch (IOException e) {
closeConnection();
}
}
}).start();
}
private void closeConnection() {
try {
connection = false;
socket.close();
inputStream.close();
outputStream.close();
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
socketIsClosed(ServerSideClient client) method works in separated thread.
public class ServerSideClient {
private Socket socket;
private InputStream in;
private OutputStream out;
private boolean connection;
private int numOfBytes;
public boolean isConnected() {
return connection;
}
public void setConnection(boolean connection) {
this.connection = connection;
}
public ServerSideClient(Socket socket) {
this.socket = socket;
try {
in = socket.getInputStream();
out = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
public void startListeningClient() {
new Thread(() -> {
listenUsers();
}).start();
}
private void listenUsers() {
while (connection == true) {
byte[] data = new byte[32 * 1024];
readInputFromClient(data);
if (numOfBytes == -1) {
try {
connection = false;
socket.close();
in.close();
out.close();
isConnected();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Client disconected..");
return;
}
String requestFromClient = new String(data, 0, numOfBytes);
System.out.println("Client sended>> " + requestFromClient);
sendResponce(requestFromClient);
}
}
private void readInputFromClient(byte[] data) {
try {
numOfBytes = in.read(data);
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendResponce(String resp) {
try {
out.write(resp.getBytes());
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I trying to resolve this problem since 2 week, Helllllllp.....
I was able to replicate your problem, and as a easy solution to fix is creating a class SocketClosedListener:
class SocketClosedListener implements Runnable {
private final ServerSideClient client;
private List<ServerSideClient> clients;
public SocketClosedListener(ServerSideClient client, List<ServerSideClient> clients) {
this.client = client;
this.clients = clients;
}
#Override
public void run() {
while (true) {
if (!client.isConnected()) {
clients.remove(client);
System.out.println("Client was removed " + clients.size());
return;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
And inside your run() method in the Connector class, we have this call:
#Override
public void run() {
while (true) {
try {
System.out.println("Waiting for clients..");
triger = true;
socket = serverSocket.accept();
System.out.println("Client connected");
ServerSideClient client = createClient();
client.setConnection(true);
client.startListeningClient();
clients.add(client);
new Thread(new SocketClosedListener(client, clients)).start();//added
} catch (IOException e) {
e.printStackTrace();
}
}
}
The line added:
new Thread(new SocketClosedListener(client, clients)).start();
It is responsible to be looking for client when disconnected in a separated thread. Also a delay of 100ms to avoid checking each ms that can cause issues when multiple threads running.
With this code I was able to have this in the console:
Waiting for clients..
Client sended>> hi
Client disconected..
Client was removed 1
Client disconected..
Client was removed 0
Okay, I decided this problem with javaRX library. I just used event that send to observer server state. In Observable class I've created:
private PublishSubject<Boolean> subject = PublishSubject.create();
public Observable<Boolean> observable = subject.asObservable();
public void setConnection(boolean connection) {
this.connection = connection;
subject.onNext(this.connection);
}
Method setConnection() set true if client has been connected and false if client initialized disconnect.
In Observer class I initialized an instance of Observable class, and initialized subscription:
client = createClient();
client.observable.subscribe(state -> removeClient(state));
public void removeClient(Boolean state) {
System.out.println("Server state " + state);
if (state == false) {
clients.remove(client);
System.out.println("Client remowed. List size: " + clients.size());
}
}
Now, I always know about server state, and make client removing if last has initialized disconnection.

Java reading from a server on port returns -1

I have to write a socket program to communicate with a server on a given port and DNS. The communication can be a single message or a list of messages; against every message a response is generated from the server. Once a connection is made I receive a response for the first message, but on the next message receive a response of -1. The following is the class handling client server communication:
public class SocketCommunication {
static String[] adresses = null;
final static int port = 1234;
final static int timeout = 60000;
static long pbmId;
private static int count = 0;
private static void loadPBMDNS()
{
DynamicQuery pbmQuery = PH_PBM_SwitchLocalServiceUtil.dynamicQuery();
pbmQuery.add(RestrictionsFactoryUtil.eq("Activated", true));
try
{
List<PH_PBM_Switch> pbmList = PH_PBM_SwitchLocalServiceUtil.dynamicQuery(pbmQuery);
if(pbmList != null && pbmList.size() > 0)
{
if(pbmList.get(0).getServer_DNS() != null
&& !pbmList.get(0).getServer_DNS().equals(""))
{
pbmId = pbmList.get(0).getPBM_Switch_Id();
if(pbmList.get(0).getServer_DNS().contains(";"))
{
String[] tokens = pbmList.get(0).getServer_DNS().split(";");
System.out.println(tokens.toString());
adresses = tokens;
}
else
{
adresses[0] = pbmList.get(0).getServer_DNS();
}
}
}
}
catch (SystemException e)
{
e.printStackTrace();
}
}
public static ArrayList<BatchClaimVO> ConnectSendAndReadResponse
(int addressNumber, ArrayList<BatchClaimVO> batchClaimVOs)
{
try
{
loadPBMDNS();
System.out.println("Connecting to " + adresses[addressNumber] + " on port " + port);
SocketFactory sslsocketfactory = SSLSocketFactory.getDefault();
SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket();
sslsocket.connect(new InetSocketAddress(adresses[addressNumber], port), timeout);
System.out.println("Just connected to " + sslsocket.getRemoteSocketAddress());
for (int i = count; i < batchClaimVOs.size(); i++)
{
sendClaim(
sslsocket,
batchClaimVOs.get(i).getCb(),
batchClaimVOs.get(i).getUniqueIdentifier()
);
if(addressNumber <= 2)
{
batchClaimVOs.get(i).setResponse
(readResponse(sslsocket, addressNumber, batchClaimVOs.get(i).getCb()));
}
}
System.out.println("Closing socket");
count = 0;
sslsocket.close();
return batchClaimVOs;
}
catch (IOException e)
{
if(addressNumber < 2)
{
System.out.println("connection timedout trying again on new DNS");
ConnectSendAndReadResponse(++addressNumber, batchClaimVOs);
}
else
{
System.out.println
("unable to connect to server or server did not responed intime");
e.printStackTrace();
}
}
return null;
}
public static void sendClaim(SSLSocket sslSocket, ClaimBuilder cb, long uniqueIdentifier)
throws IOException
{
System.out.println("sending claim");
OutputStream outToServer = sslSocket.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeBytes(cb.getClaim());
System.out.println("claim sent");
SaveRequestLog(uniqueIdentifier, cb.getClaim(), pbmId);
}
public static void SaveRequestLog(long uniqueIdentifier, String claim, long pbmId)
{
if(uniqueIdentifier > 0)
{
try
{
PH_Request_Transaction_Log log = PH_Request_Transaction_LogLocalServiceUtil.getPH_Request_Transaction_Log(uniqueIdentifier);
log.setPBM_Switch_Id(pbmId);
log.setRequest_Log(claim);
log.setCreated_By(LiferayFacesContext.getInstance().getUserId());
log.setCreated_Date(Calendar.getInstance().getTime());
PH_Request_Transaction_LogLocalServiceUtil.updatePH_Request_Transaction_Log(log);
}
catch (PortalException e)
{
e.printStackTrace();
}
catch (SystemException e)
{
e.printStackTrace();
}
}
}
public static String readResponse(SSLSocket sslSocket, int addressNumber, ClaimBuilder cb)
throws IOException
{
sslSocket.setSoTimeout(timeout);
InputStream inFromServer = sslSocket.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
byte[] data = new byte[1048];
int count = in.read(data);
System.out.println(count);
System.out.println(new String(data));
String response = fixString(new String(data), count);
System.out.println("Verifying checksum");
if(verifyTransmissionCheckSum(response))
{
System.out.println("checksum verified");
System.out.println(response);
}
else
{
System.out.println("transmission corrupted");
}
sendAcknowledgement(sslSocket, cb);
return response;
}
public static void sendAcknowledgement(SSLSocket sslSocket, ClaimBuilder cb)
throws IOException
{
System.out.println("sending Acknowledgement");
OutputStream outToServer = sslSocket.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeBytes(cb.buildClaimAcknowledgement());
System.out.println("Acknowledgement Sent");
count++;
}
public static String fixString(String toFix, int count)
{
return toFix.substring(0, count);
}
public static boolean verifyTransmissionCheckSum(String str)
{
return (Integer.parseInt((String) str.subSequence(0, 4))
== (str.subSequence(4, str.length())).length())
? true : false;
}
}
The given server do not support batch communication.

Multithreaded proxy application is not working

I'm trying to create a proxy application, but I'm facing problems in server socket. The Server Socket is not accepting the connection and returning a socket. Hence, I cannot test the proxy application. What is wrong?
The problem line is indicated in WebServe.java:
public class WebServe implements Runnable {
Socket soc;
OutputStream os;
BufferedReader is;
String resource;
WebServe(Socket s) throws IOException {
soc = s;
os = soc.getOutputStream();
is = new BufferedReader(new InputStreamReader(soc.getInputStream()));
}
public void run() {
System.err.println("Running");
getRequest();
returnResponse();
close();
}
public static void main(String args[]) {
try {
System.out.println("Proxy Thread");
ServerSocket s = new ServerSocket(8080);
for (;;) {
s.setSoTimeout(10000);
WebServe w = new WebServe(s.accept()); // Problem is here
Thread thr = new Thread(w);
thr.start();
w.getRequest();
w.returnResponse();
w.close();
}
} catch (IOException i) {
System.err.println("IOException in Server");
}
}
void getRequest() {
System.out.println("Getting Request");
try {
String message;
while ((message = is.readLine()) != null) {
if (message.equals("")) {
break;
}
System.err.println(message);
StringTokenizer t = new StringTokenizer(message);
String token = t.nextToken();
if (token.equals("GET")) {
resource = t.nextToken();
}
}
} catch (IOException e) {
System.err.println("Error receiving Web request");
}
}
void returnResponse() {
int c;
try {
FileInputStream f = new FileInputStream("." + resource);
while ((c = f.read()) != -1) {
os.write(c);
}
f.close();
} catch (IOException e) {
System.err.println("IOException is reading in web");
}
}
public void close() {
try {
is.close();
os.close();
soc.close();
} catch (IOException e) {
System.err.println("IOException in closing connection");
}
}
}
public static void main(String args[]){
try {
System.out.println("Proxy Thread");
ServerSocket s = new ServerSocket (8080);
for (;;){
s.setSoTimeout(10000);
Move that ahead of the loop. You don't need to keep setting it. You don't really need it at all actually.
WebServe w = new WebServe (s.accept()); //Problem is here
The problem is here only because you set a socket timeout you don't actually need.
Thread thr = new Thread (w);
thr.start();
So far so good.
w.getRequest();
w.returnResponse();
w.close();
Remove. The next problem is here. The run() method of WebServ already does this.
As to the rest, you aren't writing an HTTP header in the response.

TCP server madness - Slow and Merged data

I recently started to make a 2d java game, now I began the TCP server, though the server runs insanely slow (Average of 2 seconds) and I can't figure out how to stop the input stream from metering all the data into one string. I would greatly appreciate it if someone is able to help me.
ServerCode:
package com.diedericksclan.main.network;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
public class ServerThread extends Thread {
private ServerHandler server;
private ServerSocket dataSocket;
private Socket socket;
private InetSocketAddress address;
private int megabyte = 1024 * 1024;
private int dedicated = 1024;
public int RAM = megabyte * dedicated;
private WriteData send;
private ReadData read;
public ServerThread(ServerHandler server, String serverIP, int ram, int backlog) throws Exception {
this.server = server;
this.dedicated = ram;
//System.out.println(serverIP);
String ip = "localhost";
int port = 2048;
if(serverIP.contains(":")) {
ip = serverIP.split(":")[0];
port = Integer.parseInt(serverIP.split(":")[1]);
} else {
ip = serverIP;
port = 2048;
}
//System.out.println("Makin' the server");
this.dataSocket = new ServerSocket(port, backlog, InetAddress.getByName(ip));
this.address = new InetSocketAddress(dataSocket.getInetAddress(), port);
this.send = new WriteData();
this.read = new ReadData();
//System.out.println("Makin' the data handlers");
//System.out.println("Server has been made, details: " + address.getAddress() + ":" + address.getPort());
}
public ServerThread(ServerHandler server, String ip) throws Exception {
this(server, ip, 1024, 0);
}
public void run() {
//System.out.println("made");
this.send.start();
this.read.start();
while(true) {
try {
socket = dataSocket.accept();
socket.setReceiveBufferSize(megabyte);
socket.setSendBufferSize(megabyte);
socket.setTcpNoDelay(true);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void sendData(byte[] data, InetAddress IPaddress, int port) {
this.send.sendData(data, IPaddress, port);
}
public void serverShutdown() {
try {
this.dataSocket.close();
if(this.socket != null) this.socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public class WriteData extends Thread {
public WriteData() {}
public void sendData(byte[] data, InetAddress IPaddress, int port) {
try {
System.out.println("[" + System.currentTimeMillis() + "] Sending... " + new String(data));
socket.getOutputStream().write(data);
socket.getOutputStream().flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class ReadData extends Thread {
public ReadData() {}
public void run() {
try {
this.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
byte[] data;
while(true) {
try {
data = new byte[megabyte];
socket.getInputStream().read(data);
System.out.println("[" + System.currentTimeMillis() + "] Server has read, " + new String(data) + ", details: " + socket.getLocalAddress().getHostName() + ":" + socket.getLocalPort());
server.parsePacket(data, socket.getInetAddress(), socket.getPort());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
ClientCode:
package com.diedericksclan.main.network;
import java.io.*;
import java.net.*;
public class ClientThread extends Thread {
private ClientHandler client;
private Socket socket;
private InetSocketAddress address;
private int megabyte = 1024 * 1024;
private WriteData send;
private ReadData read;
public ClientThread(ClientHandler client) {
this.client = client;
this.address = new InetSocketAddress("192.168.1.2", 2048);
socket = new Socket();
try {
socket.setSendBufferSize(megabyte);
socket.setSendBufferSize(megabyte);
socket.setTcpNoDelay(true);
socket.connect(address);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println("Made client");
this.send = new WriteData();
this.read = new ReadData();
//System.out.println("Client has been made, details: " + socket.getLocalAddress() + ":" + socket.getLocalPort());
}
public void run() {
//System.out.println("made");
this.send.start();
this.read.start();
}
public void sendData(byte[] data) {
this.send.sendData(data);
}
public void serverShutdown() {
try {
this.socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public class WriteData extends Thread {
public WriteData() {}
public void sendData(byte[] data) {
try {
//System.out.println("[" + System.currentTimeMillis() + "] Sending... " + new String(data) + " to: " + socket.getInetAddress() + ":" + socket.getPort());
socket.getOutputStream().write(data);
socket.getOutputStream().flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class ReadData extends Thread {
public ReadData() {}
public void run() {
byte[] data;
while(true) {
try {
data = new byte[megabyte];
socket.getInputStream().read(data);
System.out.println("[" + System.currentTimeMillis() + "] Server data recived, " + new String(data).trim());
client.parsePacket(data, socket.getInetAddress(), socket.getPort());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
I did try to improve speed by making 2 separate threads for reading and writing data, in both the client and server, yet there was no improvement,
You have a few problems.
you allow any number of threads to write to the same socket at the same time. This makes developing a protocol very hard.
you need a protocol so you know where a message starts and end. e.g. you send the length first.
you ignore how many bytes where read. The minimum will be 1 and you can get any number of messages up to the size of the buffer at once. TCP is a stream protocol, not a messaging protocol.
If you have a reader and writer process on the same machine you should be able to get the latency to around 10 micro-seconds. (0.000010 seconds)
EDIT here is a simple example
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class PlainIOSample {
static final int RUNS = 1000000;
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(0);
DataSocket ds = new DataSocket(new Socket("localhost", ss.getLocalPort()));
DataSocket ds2 = new DataSocket(ss.accept());
long start = System.nanoTime();
for (int i = 0; i < RUNS; i++) {
// send a small message
ds.write(new byte[64]);
// receive the same message
byte[] bytes = ds2.read();
if (bytes.length != 64)
throw new AssertionError();
}
long time = System.nanoTime() - start;
System.out.printf("Average time to send/recv was %.1f micro-seconds%n",
time / RUNS / 1e3);
ds.close();
ds2.close();
}
static class DataSocket implements Closeable {
private final DataOutputStream dos;
private final DataInputStream dis;
private final Socket socket;
public DataSocket(Socket socket) throws IOException {
dos = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
this.socket = socket;
}
public void write(byte[] message) throws IOException {
synchronized (dos) {
dos.writeInt(message.length);
dos.write(message);
dos.flush();
}
}
public byte[] read() throws IOException {
synchronized (dis) {
int length = dis.readInt();
byte[] bytes = new byte[length];
dis.readFully(bytes);
return bytes;
}
}
#Override
public void close() throws IOException {
socket.close();
}
}
}
prints
Average time to send/recv was 3.3 micro-seconds

Categories