Socket and InputStream => Connection reset by peer exception - java

I'm trying to stream an InputStream's data to a socket that acts as proxy. The reason for that is, that I want to play InputStreams via the android MediaPlayer.
The problem is I always get a endto failed: ECONNRESET (Connection reset by peer) exception:
com.prom.gallery.classes.VideoProxy: [VideoProxy-172] sendto failed: ECONNRESET (Connection reset by peer)
java.net.SocketException: sendto failed: ECONNRESET (Connection reset by peer)
at libcore.io.IoBridge.maybeThrowAfterSendto(IoBridge.java:546)
at libcore.io.IoBridge.sendto(IoBridge.java:515)
at java.net.PlainSocketImpl.write(PlainSocketImpl.java:504)
at java.net.PlainSocketImpl.access$100(PlainSocketImpl.java:37)
at java.net.PlainSocketImpl$PlainSocketOutputStream.write(PlainSocketImpl.java:266)
at com.prom.gallery.classes.VideoProxy.processRequest(VideoProxy.java:168)
at com.prom.gallery.classes.VideoProxy.run(VideoProxy.java:110)
at java.lang.Thread.run(Thread.java:818)
Caused by: android.system.ErrnoException: sendto failed: ECONNRESET (Connection reset by peer)
at libcore.io.Posix.sendtoBytes(Native Method)
at libcore.io.Posix.sendto(Posix.java:176)
at libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:278)
at libcore.io.IoBridge.sendto(IoBridge.java:513)
at java.net.PlainSocketImpl.write(PlainSocketImpl.java:504) 
at java.net.PlainSocketImpl.access$100(PlainSocketImpl.java:37) 
at java.net.PlainSocketImpl$PlainSocketOutputStream.write(PlainSocketImpl.java:266) 
at com.prom.gallery.classes.VideoProxy.processRequest(VideoProxy.java:168) 
at com.prom.gallery.classes.VideoProxy.run(VideoProxy.java:110) 
at java.lang.Thread.run(Thread.java:818) 
Question
How can I solve that? My solution is appended and is based on https://code.google.com/p/npr-android-app/source/browse/Npr/src/org/npr/android/news/StreamProxy.java... I found out I may need a header to keep the socket open, but I don't really know if that's true and how to add that to my solution...
My custom class IDownloadableMedia just directly returns a simple stream...
I have multiple sources with videos, some of them allow streams only. For testing I use a source that works with urls as well and I create an InputStream like following in the download function: new URL(url).openStream(). The url is valid and working!
Code
Here's my VideoProxy class:
public class VideoProxy implements Runnable
{
public static String createProxyString(VideoProxy proxy, int folderIndex, int mediaIndex, String uniqueId)
{
return String.format("http://127.0.0.1:%d/%s", proxy.getPort(), folderIndex + "-" + mediaIndex + "-" + uniqueId);
}
private int port = 0;
public int getPort()
{
return port;
}
private boolean mIsRunning = true;
private ServerSocket mSocket;
private Thread mThread;
public void init()
{
try
{
mSocket = new ServerSocket(port, 0, InetAddress.getByAddress(new byte[] {127, 0, 0, 1}));
mSocket.setSoTimeout(5000);
port = mSocket.getLocalPort();
L.d(this, "Port " + port);
}
catch (UnknownHostException e)
{
L.e(this, e);
}
catch (IOException e)
{
L.e(this, e);
}
}
public void start()
{
if (mSocket == null)
throw new IllegalStateException("Proxy has not been initialized!");
mThread = new Thread(this);
mThread.start();
}
public void stop()
{
mIsRunning = false;
if (mThread != null)
{
mThread.interrupt();
try
{
mThread.join(5000);
}
catch (InterruptedException e)
{
L.e(this, e);
}
}
}
#Override
public void run()
{
L.d(this, "Run...");
while (mIsRunning)
{
try
{
Socket client = mSocket.accept();
if (client == null)
continue;
L.d(this, "client connected");
// get data
String data = readData(client);
L.d(this, "data: " + data);
String splitted[] = data.split("-");
int folderIndex = Integer.parseInt(splitted[0]);
int mediaIndex = Integer.parseInt(splitted[1]);
String uniqueId = splitted[2];
L.d(this, "data splitted: " + folderIndex + ", " + mediaIndex + ", " + uniqueId);
// get media file
IDownloadableMedia media = (IDownloadableMedia)RXManager.get().createLoadedSingleFolderObservable(null, null, folderIndex).toBlocking().first().getMedia().get(mediaIndex);
L.d(this, "media: " + media.getMediaFolder().getName() + " | " + media.getName());
// download media file
processRequest(client, media);
}
catch (SocketTimeoutException e)
{
// Do nothing
}
catch (IOException e)
{
L.e(this, e);
}
}
L.d(this, "Proxy interrupted - shutting down...");
}
private String readData(Socket client)
{
InputStream is;
String firstLine;
try
{
is = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
firstLine = reader.readLine();
}
catch (IOException e)
{
L.e(this, e);
return null;
}
if (firstLine == null)
{
L.d(this, "Proxy client closed connection without a request.");
return null;
}
StringTokenizer st = new StringTokenizer(firstLine);
String method = st.nextToken();
String uri = st.nextToken();
L.d(this, uri);
String realUri = uri.substring(1);
L.d(this, realUri);
return realUri;
}
private void processRequest(Socket client, IDownloadableMedia downloadableMedia) throws IllegalStateException, IOException
{
if (downloadableMedia == null)
return;
L.d(this, "downloading...");
InputStream data = downloadableMedia.download();
try
{
int readBytes = -1;
// Stream content...
byte[] buff = new byte[1024 * 50];
while (mIsRunning && (readBytes = data.read(buff, 0, buff.length)) != -1)
client.getOutputStream().write(buff, 0, readBytes);
}
catch (Exception e)
{
L.e(this, e);
}
finally
{
if (data != null)
data.close();
client.close();
}
}
}

Related

Why does my Socket client only receive 1 packet?

I have a chess server and client that I made in Java that transfers packets to each other. When a client connects, the server sends a packet back to the client. My program always detects this packet. After that when I try to move a piece, a packet is sent to the server and the server detects it. It prints the packet string to the client which the client uses to move the piece, but the client never reads it. How do I fix this?
Connection superclass:
public class ChessConnection {
protected Socket socket;
protected PrintWriter output;
protected BufferedReader input;
public void listen() {
try {
String line;
while ((line = input.readLine()) != null) {
this.inputReceived(line);
}
} catch (SocketException e) {
System.out.println("SocketException: " + e.getMessage());
} catch (IOException e) {
System.out.println("IOException: " + e.getMessage());
e.printStackTrace();
}
}
public void sendPacket(Packet packet) {
output.println(packet.serialize());
};
public void inputReceived(String input) {}
}
ClientConnection (Client side):
public class ClientConnection extends ChessConnection {
public ClientConnection() {
try {
socket = new Socket("localhost", 4141);
output = new PrintWriter(socket.getOutputStream(), true);
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (HeadlessException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
System.out.println("Host is unknown");
} catch (IOException e) {
e.printStackTrace();
}
new Thread(this::listen).start();
}
#Override
public void listen() {
try {
String line;
while ((line = input.readLine()) != null) {
System.out.println("client received input: " + line); // This doesn't print the move piece packet, but it does print the connection packet
this.inputReceived(line);
}
} catch (SocketException e) {
System.out.println("SocketException: " + e.getMessage());
} catch (IOException e) {
System.out.println("IOException: " + e.getMessage());
e.printStackTrace();
}
}
}
ServerConnection (Server side):
public class ServerConnection extends ChessConnection {
private static int NEXT_ID = 1;
private static ArrayList<ServerConnection> clients = new ArrayList<ServerConnection>();
public int connectionId;
public ServerHandler handler;
public ServerConnection(ServerHandler handler, Socket socket) {
this.connectionId = NEXT_ID++;
this.handler = handler;
try {
this.socket = socket;
this.output = new PrintWriter(socket.getOutputStream(), true);
this.input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (Exception e) {
e.printStackTrace();
}
new Thread(this::listen).start(); // Starts listening to client
System.out.println("Client " + this.connectionId + " connected");
sendPacket(new ConnectionPacket());
}
#Override
public void listen() {
try {
String line;
while ((line = input.readLine()) != null) {
this.inputReceived(line);
}
} catch (SocketException e) {
System.out.println("SocketException: " + e.getMessage());
handler.broadcastPacket(new DisconnectionPacket());
System.out.println("Client " + this.getId() + " disconnected");
} catch (IOException e) {
System.out.println("IOException: " + e.getMessage());
e.printStackTrace();
}
}
#Override
public void inputReceived(String input) {
System.out.println("server received input: " + input);
Packet packet = Packet.toPacket(input);
switch (packet.getType()) {
case Packet.DISCONNECTION:
break;
case Packet.CONNECTION:
break;
case Packet.PIECE_MOVE:
System.out.println("sending move piece");
handler.broadcastPacket(packet);
break;
case Packet.PAWN_REPLACEMENT:
break;
default:
System.out.println("Received malformed packet: " + input);
break;
}
}
public int getId() {
return this.connectionId;
}
public static ServerConnection getClientFromId(int clientId) {
for (ServerConnection client : clients) {
if (client.getId() == clientId) {
return client;
}
}
return null;
}
}

Android studio trying to connect lots of ports on local (port 5037 time_await)

I am trying to make a client/server connection using SOCKETS.
Server side is Java in Eclipse,
Client side is in Android Studio.
There is some codes in both server and client sides for socket connection.
The connection was SUCCESSFUL yesterday.Today, I tried to connect to server with android app client, I have FAİLED.
When I check connections from netstat -a -n , I saw this:
(When I open the client)
That's weird because I have seen this ports before connection codes work.And the ports increases.
And Server Codes:
public class CapitalizeServer {
static ArrayList<Client> clients = new ArrayList<>();
public static void main(String[] args) throws Exception {
System.out.println("The capitalization server is running.");
int clientNumber = 0;
ServerSocket listener = new ServerSocket(44057);
try {
while (true) {
new Capitalizer(listener.accept(), clientNumber++).start();
}
} finally {
listener.close();
}
}
private static class Capitalizer extends Thread {
private Socket socket;
private int clientNumber;
private String uname,pass;
private boolean checked;
public Capitalizer(Socket socket, int clientNumber) {
this.socket = socket;
this.clientNumber = clientNumber;
log("New connection with client# " + clientNumber + " at " + socket);
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String input = in.readLine();
if(input.substring(0, "uname:".length()).equals("uname:")){
this.uname = input.substring(6);
}else{
return; //Programı durdur
}
input = in.readLine();
if(input.substring(0,"pass:".length()).equals("pass:")){
this.pass = input.substring(5);
}else{
return; //Programı durdur
}
if(this.pass != null && !checked){
if(checkPass() == 1){
//Yanıt olumlu olduğu için bağlantı clientlar arasına eklenir.
Client cc = new Client(uname, pass, socket, 0, 1);
clients.add(cc);
checked = true;
}else{
//Yanıt olumuz ise bağlantı koparılır.
socket.close();
log("Socket Closed!" + socket);
checked = true;
}
}
while (true) {
if (input == null || input.equals(".")) {
break;
}
//Mesajlar iletilir.
if(input.substring(0,3)=="com:"){
switch (input.substring(4,5)) {
case "1": //Attack başlat 1 şİMDİLİK SADECE BU SEÇENEK AKTİF
//pHp ile random person belirle. (uname döndürür.)
//clients arrayında olup olmadığını kontrol et.(online mı ve savaşta mı)
//->eğer online ise, savaşta olup olmadığına bak
// eğer savaşta ise saldırılmaz.
// Eğer savaşta değil ise saldır, socket ile onu da savaş alanına al
//->Eğer online değil ise savaşı başlat.Adama da mesaj at.
attack1();
break;
case "2": //Attack başlat 2
break;
case "3": //Attack başlat 3
break;
case "4": //Attack başlat 4
break;
default:
break;
}
}
}
} catch (IOException e) {
log("Error handling client# " + clientNumber + ": " + e);
} finally {
try {
socket.close();
} catch (IOException e) {
log("Couldn't close a socket, what's going on?");
}
log("Connection with client# " + clientNumber + " closed");
}
}
public void attack1(){
try {
// open a connection to the site
URL url = new URL("http://localhost/attack/attack.php");
URLConnection con = url.openConnection();
// activate the output
con.setDoOutput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
// send your parameters to your site
ps.print("firstKey=firstValue");
ps.print("&secondKey=secondValue");
// we have to get the input stream in order to actually send the request
//con.getInputStream();
// close the print stream
ps.close();
BufferedReader cin = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while ((line = cin.readLine()) != null) {
System.out.println(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public int checkPass(){
//Connect to db and check the pass and uname
//Php kodları arasında check işlemini yapan url'yi çalıştır
//Yanıt olumlu ise 1, değilse 0 döndür.
try {
// open a connection to the site
URL url = new URL("http://localhost/userControls/singin.php");
URLConnection con = url.openConnection();
// activate the output
con.setDoOutput(true);
//con.setDoInput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
// send your parameters to your site
ps.print(URLEncoder.encode("uname","UTF-8") + "=" + URLEncoder.encode(uname, "UTF-8"));
ps.print(URLEncoder.encode("&pass=","UTF-8")+ "=" + URLEncoder.encode(pass, "utf-8"));
ps.close();
System.out.println("111111");
BufferedReader cin = new BufferedReader(new InputStreamReader(con.getInputStream()));
System.out.println("222222");
String line = null;
while ((line = cin.readLine()) != null) {
System.out.println(":::::::Geldik la Geldiiiik::::::::: " + line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return 1;
}
private void log(String message) {
System.out.println(message);
}
}
}
And clients first activitys code:
public class SignInMenu extends ActionBarActivity {
Button button18;
EditText et1,et2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signin_menu);
button18 = (Button) findViewById(R.id.button18);
et1 = (EditText) findViewById(R.id.editText);
et2 = (EditText) findViewById(R.id.editText2);
}
public void button18Click(View view){
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("uname",et1.getText().toString());
intent.putExtra("pass",et2.getText().toString());
startActivity(intent);
}
}
I am using WAMP Server.
And there is something weird about it.I cant access localhost using my local ip(192.168.1.36). Only with this: http://localhost/
When i try to connect with my local ip, the error like this:192.168.1.36 refused connection.
Maybe this is about the problem.
So how can i solve this problem?
EDİT:(NEW PROBLEM)
*Problem is about java-php connection now.
My server connects to php for queries.Here is the code for connect to php page.I take error in line "PrintStream ps = new PrintStream(con.getOutputStream());".
And the error says: Connection refused:connect
try{
// open a connection to the site
URL url = new URL("http://192.168.1.35/userControls/singin.php");
URLConnection con = url.openConnection();
// activate the output
con.setDoOutput(true);
//con.setDoInput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
// send your parameters to your site
ps.print(URLEncoder.encode("uname","UTF-8") + "=" + URLEncoder.encode(uname, "UTF-8"));
ps.print(URLEncoder.encode("&pass=","UTF-8")+ "=" + URLEncoder.encode(pass, "utf-8"));
ps.close();
BufferedReader cin = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while ((line = cin.readLine()) != null) {
System.out.println(":::::::Worked::::::::: " + line);
}
}/* catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}*/ catch (Exception e) {
System.out.println("Eror:" + e.getMessage());
}
How can i solve this second problem?

how to detect client's Internet speed from the response headers in java?

I have a server to get a response headers through which I detect the type of device. Is there any way I can get the Internet speed through response headers or any other method ?
Server_X:
public class Server_X {
static int count = 0;
public static void main(String args[]) {
Socket s = null;
ServerSocket ss2 = null;
System.out.println("Server Listening......");
try {
// can also use static final PORT_NUM, when defined
ss2 = new ServerSocket(4445);
} catch (IOException e) {
e.printStackTrace();
System.out.println("Server error");
}
while (true) {
try {
s = ss2.accept();
System.out.println("connection Established");
ServerThread st = new ServerThread(s);
count++;
System.out.println("total connections :" + count);
st.start();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("Connection Error");
}
}
}
}
ServerThread:
class ServerThread extends Thread {
static String uagent, uaccept;
static String[] b;
static String[] c;
Server_X obj = new Server_X();
String line = null;
BufferedReader is = null;
PrintWriter os = null;
Socket s = null;
public ServerThread(Socket s) {
this.s = s;
}
public void run() {
try {
is = new BufferedReader(new InputStreamReader(s.getInputStream()));
os = new PrintWriter(s.getOutputStream());
} catch (IOException e) {
System.out.println("IO error in server thread");
}
try {
line = is.readLine();
while (line.compareTo("QUIT") != 0) {
os.println(line);
os.flush();
// System.out.println(line);
line = is.readLine();
b = line.split(":");
if (b[0].equals("User-Agent")) {
uagent = b[1];
// System.out.println(uagent);
}
c = line.split(":");
if (c[0].equals("Accept")) {
uaccept = c[1];
// System.out.println(uaccept);
}
UAgentInfo detect = new UAgentInfo(uagent, uaccept);
}
} catch (IOException e) {
line = this.getName(); // reused String line for getting thread name
// System.out.println("IO Error/ Client "+line+" terminated abruptly");
} catch (NullPointerException e) {
line = this.getName(); // reused String line for getting thread name
// System.out.println("Client "+line+" Closed");
} finally {
try {
System.out.println("Connection Closing..");
if (is != null) {
is.close();
// System.out.println(" Socket Input Stream Closed");
}
if (os != null) {
os.close();
// System.out.println("Socket Out Closed");
}
if (s != null) {
s.close();
// System.out.println("Socket Closed");
obj.count--;
System.out.println("Toatal connections (after closing):"
+ obj.count);
}
} catch (IOException ie) {
// System.out.println("Socket Close Error");
}
}// end finally
}
}
You didn't specify what protocol the server is using; I suppose is HTTP since you're catching "User-Agent" and "Accept". If I'm correct, there's no header with the information you're looking for, as you can check on https://en.wikipedia.org/wiki/List_of_HTTP_header_fields.

Coding a MultiThreaded Socket Proxy: IOException SocketClosed where it shouldn't

I just started coding a proxy for TCP Socket Connections and although i'm checking if the Sockets are still open i'm getting a IOException.
This is the LOC which is causing it. Anybody has an idea why this can happen?
while (!from.isClosed() && !to.isClosed() && (numOfBytes = in.read(byteBuffer)) != -1)
I've already debugged the code; from & to are not closed when they are checked.
for context:
Proxy.java
public class Proxy
{
public static void main(String[] args)
{
try (ServerSocket proxyServer = new ServerSocket(5432))
{
int i = 0;
while (true)
{
Socket client = proxyServer.accept();
System.out.println(i++);
Socket server = new Socket("localhost", 5000);
ProxyHandler clientToServer = new ProxyHandler(client, server);
ProxyHandler serverToClient = new ProxyHandler(server, client);
clientToServer.setName("client->server"+i);
serverToClient.setName("server->client"+i);
clientToServer.start();
serverToClient.start();
System.out.println("proxy started");
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
ProxyHandler.java
public class ProxyHandler extends Thread
{
private Socket from;
private Socket to;
public ProxyHandler(Socket from, Socket to)
{
this.from = from;
this.to = to;
}
#Override
public void run()
{
try (DataInputStream in = new DataInputStream(from.getInputStream());
DataOutputStream out = new DataOutputStream(to.getOutputStream()))
{
byte[] byteBuffer = new byte[1024];
int numOfBytes = 0;
while (!from.isClosed() && !to.isClosed() && (numOfBytes = in.read(byteBuffer)) != -1)
{
out.write(byteBuffer, 0, numOfBytes);
out.flush();
System.out.println(getName() + "(" + numOfBytes + ") ");
System.out.println(new String(byteBuffer, "UTF-8"));
}
System.out.println("left : " + getName());
}
catch (IOException io)
{
System.out.println("IOException: " + io.getMessage() + " " + getName());
io.printStackTrace();
}
}
}
isClosed() only returns true if you, yourself, have explicitly closed the socket. It can not be used to detect unexpected disconnects.

How to implement TCP connection pooling in java? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Here, I managed to get a connection between a single server and single client but now my new hurdle is how to achieve a pool of TCP connections on client side in Java. I have gone through many sites, but at the end no fruitful solution was found. Here the class which I had used for obtaining connection to a server:
public class TCPIPCommunicator {
private final String MODULE="TCPIPCommunicator :";
//private DeviceEntity deviceEntity;
private static InetAddress inetServer = null;
private static int devicePort = -1;
private Socket clientSocket;
private BufferedOutputStream outputStream;
private BufferedInputStream inputStream;
private static boolean isLinkActive = false;
private String IP="";
public TCPIPCommunicator(String IP, int devicePort) {
this.IP=IP;
this.devicePort=devicePort;
initialize();
}
public static boolean isLinkActive(){
return isLinkActive;
}
public static void setLinkStatus(boolean status){
isLinkActive = status;
}
private void initialize() {
System.out.println(MODULE+ "Inside initialize()" );
setLinkStatus(false);
try{
inetServer = InetAddress.getByName(IP);
}catch (UnknownHostException uhe) {
System.out.println(MODULE+ "Error while creating inetaddress, Reason:"+uhe.getMessage());
}
System.out.println(MODULE+ "Connecting to - " +inetServer.getHostAddress() + ":" + devicePort);
establishConnection();
if(!isLinkActive()){
//sendNotification(TCPIPConstants.LINK_DOWN);
releaseResources();
//resumeLinkSanityHelper();
}
System.out.println(MODULE+ "out of initialize(), isLinkActive :" + isLinkActive() );
}
public boolean establishConnection(){
boolean isConnected = false;
//Get the Connection to PMS Server.
if(inetServer != null && devicePort > 0){
try{
clientSocket = new Socket(inetServer, devicePort);
clientSocket.setKeepAlive(true);
}catch(ConnectException ce){
ce.printStackTrace();
setLinkStatus(false);
System.out.println(MODULE+ "Exception in initialize() " + "Couldnot Connect Server. Reason:"+ce.getMessage());
}catch(Exception e){
e.printStackTrace();
setLinkStatus(false);
System.out.println(MODULE+ "Exception in initialize() " + "while creating socket ,Reason: " + e.getMessage());
}
//If got connection, Get the streams.
if(clientSocket != null && !clientSocket.isClosed()){
System.out.println(MODULE+ "in initialize(), Got Socket Connection." );
try{
outputStream = new BufferedOutputStream(clientSocket.getOutputStream());
}catch(Exception e){
e.printStackTrace();
outputStream=null;
setLinkStatus(false);
System.out.println(MODULE+ "Exception in initialize() while getting socket outputStream : " + e.getMessage());
}
if(outputStream != null){
try{
inputStream = new BufferedInputStream(clientSocket.getInputStream());
}catch(Exception e){
setLinkStatus(false);
System.out.println(MODULE+ "Exception in initialize() " + "while getting socket inputStream : " + e.getMessage());
}
setLinkStatus(true);
}
if(outputStream != null && inputStream != null){
isConnected = true;
}
}else{
System.out.println(MODULE+ "in initialize(), Connection is closed or null." );
setLinkStatus(false);
}
}
return isConnected;
}
public int writeData(byte[] msg){
int retValue = -1;
try{
if(isLinkActive() && (outputStream !=null)){
System.out.println(MODULE+ "Writting data ::::" + new String(msg)+ "::::");
outputStream.write(msg);// ed
outputStream.flush();
retValue = 1;
}else{
System.out.println(MODULE+ " in writeData() link is down so status:" + retValue );
}
}catch(Exception e){
e.printStackTrace();
retValue = -1;
System.out.println(MODULE+ "Exception in write() < message to be sent was = " + new String(msg) + " > : " + e.getMessage());
}
if(retValue == -1 && isLinkActive()){
setLinkStatus(false);
//sendNotification(TCPIPConstants.LINK_DOWN);
//releaseResources();
//resumeLinkSanityHelper();
}
System.out.println(MODULE+ " in writeData() Write status for ::"+ new String(msg) + ":: -->" +retValue);
return retValue;
}
public String readData() {
System.out.println(MODULE+"\tInside readDAta");
String response = null;
int bytesReceived=-1;
byte[] readBuffer = new byte[1024];
try{
long timetoread = System.currentTimeMillis();
if(inputStream == null || !(isLinkActive())){
System.out.println(MODULE+"Inputstream is null or link is down, returning null");
return null;
}
try{
System.out.println("Waiting to read data");
bytesReceived = inputStream.read(readBuffer);
System.out.println(MODULE+"# Byte Receieved #" + bytesReceived);
}catch(Exception e){
e.printStackTrace();
System.out.println(MODULE+"Error in readData() , Reason:"+e.getMessage());
if(isLinkActive()){
setLinkStatus(false);
//sendNotification(TCPIPConstants.LINK_DOWN);
releaseResources();
//resumeLinkSanityHelper();
}
}
if(bytesReceived > 0){
response = new String(readBuffer,0,bytesReceived); // ed
timetoread = System.currentTimeMillis() - timetoread;
System.out.println(MODULE + "Total Bytes Received: " + bytesReceived);
System.out.println(MODULE+ "Total Time Taken : " + timetoread);
System.out.println(MODULE+ "Length of data received : " + response.length());
System.out.println(MODULE+ "Data Received : ####" + response + "####");
}else{
////////// HERE MEANS TCP CONNECTION STATUS WILL CLOSE_WAIT
////////// SO RELEASING CONNECTION.
System.out.println(MODULE+ " Releasing Resource. bytesReceived is <= 0 : Total Bytes Received :"+ bytesReceived );
if(isLinkActive()){
setLinkStatus(false);
//sendNotification(TCPIPConstants.LINK_DOWN);
releaseResources();
//resumeLinkSanityHelper();
}
System.out.println(MODULE+ " Resource has been released.");
}
}catch(Exception e){
e.printStackTrace();
System.out.println(MODULE+ "In catch : Data Received : ####" + response + "####");
System.out.println(MODULE+ "Exception in readdata() : " + e);
}finally{
readBuffer=null;
}
return response;
}
public void releaseResources(){
System.out.println(MODULE+ "Releasing Resources....");
try{
if(clientSocket !=null)
clientSocket.close();
}catch(Exception e){
System.out.println(MODULE+ "In releaseResources() :Error closing socket."+e.getMessage());
}
try{
if(inputStream !=null )
inputStream.close();
}catch(Exception e){
System.out.println(MODULE+ "In releaseResources() :Error closing inputStream."+e.getMessage());
}
try{
if(outputStream != null){
outputStream.close();
}
}catch(Exception e){
System.out.println(MODULE+ "in releaseResources() :Error closing outputStream.");
}
System.out.println(MODULE + "Resources Relased...");
}
}
Here establishConnection() method will be establish the connection to the server.
Note: I was thinking on using ThreadPoolExecutor, but as the requirement is for synchronous, I dropped this idea of using it.
The sample code is like below,I use a Map ,the key is "host-port" ,and the value is a LinkedList containing the sockets related to the same url.
public class SocketPool{
Map<String,LinkedList<Socket>> sockets;
public boolean establishConnection(String inetServer , int devicePort){
boolean result = false;
try {
Socket clientSocket = new Socket(inetServer, devicePort);
String socketKey = inetServer + "-" + devicePort;
if(clientSocket.isConnected()&&sockets.containsKey(socketKey)){
sockets.get(socketKey).add(clientSocket);
}else if(clientSocket.isConnected()&&!sockets.containsKey(socketKey)){
LinkedList<Socket> socketSet = new LinkedList<Socket>();
socketSet.add(clientSocket);
sockets.put(socketKey, socketSet);
}
result = true;
} catch (UnknownHostException e) {
result = false;
} catch (IOException e) {
result = false;
}
return result;
}
public Socket fetchSocket(String inetServer , int devicePort){
String socketKey = inetServer + "-" + devicePort;
Socket clientSocket =null;
if(sockets.containsKey(socketKey)&&!sockets.get(socketKey).isEmpty()){
clientSocket = sockets.get(socketKey).removeLast();
int size = sockets.get(socketKey).size();
if(size==0){
sockets.remove(socketKey);
}
}
return clientSocket;
}
//other functions
}
You can create a variable Set<Socket> to store all the client Sockets you created. Every time you connect to the server socket you can put the client
socket into this set. This set works as the pool.

Categories