Hi i have written a server program to receive ISO8583-93 version requests process them and send response.I will be receiving continuous requests.It works fine ,but if socket is idle when the next request comes, server is not reading.
Please find below code snippet
SERVER :
public class MBServ {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listening = true;
String request_date = null;
String request_time = null;
try {
serverSocket = new ServerSocket(7777);
} catch (IOException e) {
System.err.println("Could not listen on port: 7777.");
System.exit(-1);
}
while (listening) {
new MBServT(serverSocket.accept()).start();
}
serverSocket.close();
}
}
THREAD:
public class MBServT extends Thread {
private Socket socket = null;
Logger log = Logger.getLogger(MBServT .class.getName());
public MBServT(Socket socket) throws FileNotFoundException, IOException {
super("MBServT");
this.socket = socket;
}
public void run() {
String inputLine = "";
String msgType = null;
int response = 12;
String outwardMsg = null;
BufferedReader buffReaderObj = null;
// String ip = "172.30.12.69";
String stanNo = "0";
boolean ISSUBFIELDPARSING = false;
GenericPackager packager;
try {
packager = new GenericPackager("basicparse.xml");
BufferedReader is = new BufferedReader(new InputStreamReader(socket
.getInputStream(), "ISO8859_1"));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream(), "ISO8859_1"));
String strBuf = null;
int length = 4;
char[] chrBuf = new char[length];
int cnt = 0;
while (true) {
socket.setKeepAlive(true);
int value = 0;
int ret = 0;
ret = is.read(chrBuf, 0, chrBuf.length);
if (-1 == ret)
{
log.error("nothing to read closing socket");
try{
socket.close();
}
catch(Exception e){
System.out.println("Error in socket.close: " +e.toString());
}
throw new Exception("Read Error: Socket closed");
}
strBuf = new String(chrBuf);
chrBuf = new char[Integer.parseInt(strBuf)];
is.read(chrBuf, 0, chrBuf.length);
strBuf = new String(chrBuf);
chrBuf = null;
chrBuf = new char[4];
value = 0;
/*writing response*/
Runnable respThread = new MBServRespT(writer, fieldList,
"threadname");
((Thread) respThread).start();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Error::" + e.toString());
} finally {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
It worked after we implemented set sockettimeout.
Related
I'm trying to make a program that has a client, and intermediate host and a server. The client sends a packet to the host, the host sends it to the server and than the server sends a packet back to the host who sends it to the client. This should repeat 11 times.
Here is my code:
public class SimpleEchoClient {
DatagramPacket sendPacket, receivePacket;
DatagramSocket sendReceiveSocket;
public SimpleEchoClient()
{
try {
sendReceiveSocket = new DatagramSocket();
} catch (SocketException se) { // Can't create the socket.
se.printStackTrace();
System.exit(1);
}
}
public byte[] createWriteByte() {
byte[] msg = new byte[100];
int position = 2;
Path path = Paths.get("test.txt");
String fileName = path.getFileName().toString();
//In datagrampackets, our data needs to be converted into bytes
msg = new byte[100];
msg[0] = 0x00;
msg[1] = 0x02;
for(int i=0; i<fileName.getBytes().length; i++) {
msg[position] = fileName.getBytes()[i];
position++;
}
msg[position] = 0x00;
String mode = "netascii";
position++;
for(int i = 0; i < mode.getBytes().length; i++) {
msg[position] = mode.getBytes()[i];
position++;
}
msg[position] = 0;
return msg;
}
public byte[] createReadByte() {
byte[] msg = new byte[100];
int position = 2;
Path path = Paths.get("test.txt");
String fileName = path.getFileName().toString();
//In datagrampackets, our data needs to be converted into bytes
msg = new byte[100];
msg[0] = 0x00;
msg[1] = 0x01;
for(int i=0; i<fileName.getBytes().length; i++) {
msg[position] = fileName.getBytes()[i];
position++;
}
msg[position] = 0x00;
String mode = "netascii";
position++;
for(int i = 0; i < mode.getBytes().length; i++) {
msg[position] = mode.getBytes()[i];
position++;
}
msg[position] = 0;
return msg;
}
public void sendAndReceive(boolean checkRead)
{
Path path = Paths.get("test.txt");
String fileName = path.getFileName().toString();
//In datagrampackets, our data needs to be converted into bytes
byte[] msg;
if(checkRead) {
msg = createReadByte();
checkRead = false;
}else{
msg = createWriteByte();
checkRead = true;
}
String str = new String(msg);
System.out.println(str);
System.out.println("Hello");
System.out.println(msg);
try {
sendPacket = new DatagramPacket(msg, msg.length,
InetAddress.getLocalHost(), 5000);
} catch (UnknownHostException e) {
e.printStackTrace();
System.exit(1);
}
try {
sendReceiveSocket.send(sendPacket);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
sendReceiveSocket.close();
try {
Thread.sleep(5000);
} catch (InterruptedException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
System.out.println("Client: Packet sent.\n");
//NOW TO RECEIVE THE DATA
DatagramSocket receiveSocket = null;
try {
receiveSocket = new DatagramSocket(5000);
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte data[] = new byte[4];
receivePacket = new DatagramPacket(data, data.length);
try {
// Block until a datagram is received via sendReceiveSocket.
receiveSocket.receive(receivePacket);
} catch(IOException e) {
e.printStackTrace();
System.exit(1);
}
// Process the received datagram.
for(int j =0; j < data.length; j++) {
System.out.println(data[j] & 0xff);
}
// We're finished, so close the socket.
sendReceiveSocket.close();
}
public static void main(String args[])
{
boolean checkRead = true;
int count =0;
for(int i = 0; i<10; i++) {
System.out.println("Count:" + count);
SimpleEchoClient c = new SimpleEchoClient();
c.sendAndReceive(checkRead);
}
}
}
public class IntermediateHost {
DatagramSocket receiveFromClient, receiveFromServer;
DatagramPacket receiveClientPack, sendClientPacket, receiveServerPacket, sendServerPacket;
public IntermediateHost() {
try {
receiveFromClient = new DatagramSocket(5000);
} catch (SocketException e) {
e.printStackTrace();
}
}
public void receiveAndEcho() {
byte [] b = new byte[100];
//When we receive the packet we need to store it in a datagrampacket which is initally empty
receiveClientPack = new DatagramPacket(b, b.length);
InetAddress ip = null;
try {
receiveFromClient.receive(receiveClientPack);
ip = InetAddress.getByName("localhost");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String message = new String(b);
System.out.println(message);
System.out.println(b);
int port = 3001;
sendClientPacket = new DatagramPacket(b, b.length, ip, port);
try {
receiveFromClient.send(sendClientPacket);
} catch (IOException e1) {
e1.printStackTrace();
}
receiveFromClient.close();
//SEND BACK TO THE CLIENT
try {
Thread.sleep(5000);
receiveFromServer = new DatagramSocket(3001);
} catch (InterruptedException | SocketException e1) {
e1.printStackTrace();
}
byte [] b1 = new byte[4];
//When we receive the packet we need to store it in a datagrampacket which is initally empty
receiveServerPacket = new DatagramPacket(b1, b1.length);
//This method will wait for the incoming packet and it will copy all values from that packet
//into receiveClientPack..so at this point the byte array will not be empty
try{
receiveFromServer.receive(receiveServerPacket);
}catch (Exception e) {
System.out.println(e);
}
for(int i =0;i < b1.length; i++) {
System.out.println(b1[i] & 0xff);
}
InetAddress ip1 = null;
try {
ip1 = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
int port1 = 5000;
sendServerPacket = new DatagramPacket(b1, b1.length, ip1, port1);
try {
receiveFromServer.send(sendServerPacket);
} catch (IOException e) {
e.printStackTrace();
}
receiveFromServer.close();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String args[]) throws IOException, InterruptedException {
while(true) {
IntermediateHost inter = new IntermediateHost();
inter.receiveAndEcho();
}
}
}
public class SimpleEchoServer {
DatagramPacket sendPacket, receivePacket;
DatagramSocket sendSocket, receiveSocket;
public SimpleEchoServer()
{
try {
sendSocket = new DatagramSocket();
receiveSocket = new DatagramSocket(3001);
} catch (SocketException se) {
se.printStackTrace();
System.exit(1);
}
}
public byte[] sendBackRead() {
byte [] bytesToSend = new byte[4];
bytesToSend[0] = 0x00;
bytesToSend[1] = 0x03;
bytesToSend[2] = 0x00;
bytesToSend[3] = 0x01;
return bytesToSend;
}
public byte[] sendBackWrite() {
byte [] bytesToSend = new byte[4];
bytesToSend[0] = 0x00;
bytesToSend[1] = 0x04;
bytesToSend[2] = 0x00;
bytesToSend[3] = 0x00;
return bytesToSend;
}
public boolean checkRead(byte[] msg) {
if(msg[1] == 1) {
return true;
}
return false;
}
public boolean checkWrite(byte[] msg) {
if(msg[1] == 2) {
return true;
}
return false;
}
public void receiveAndEcho() throws UnknownHostException
{
byte data[] = new byte[100];
receivePacket = new DatagramPacket(data, data.length);
System.out.println("Server: Waiting for Packet.\n");
try {
System.out.println("Waiting..."); // so we know we're waiting
receiveSocket.receive(receivePacket);
} catch (IOException e) {
System.out.print("IO Exception: likely:");
System.out.println("Receive Socket Timed Out.\n" + e);
e.printStackTrace();
System.exit(1);
}
boolean checkRead = checkRead(data);
boolean checkWrite = checkWrite(data);
String message = new String(data);
System.out.println(message);
receiveSocket.close();
// Slow things down (wait 5 seconds)
try {
Thread.sleep(5000);
} catch (InterruptedException e ) {
e.printStackTrace();
System.exit(1);
}
byte[] bytesToSend = null;
System.out.println(data[1]);
if(checkRead) {
bytesToSend = sendBackWrite();
}else if(checkWrite) {
bytesToSend = sendBackRead();
}
for(int i =0;i < bytesToSend.length; i++) {
System.out.println(bytesToSend[i] & 0xff);
}
InetAddress ip = InetAddress.getLocalHost();
sendPacket = new DatagramPacket(bytesToSend, bytesToSend.length,
ip, 3001);
// Send the datagram packet to the client via the send socket.
try {
sendSocket.send(sendPacket);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
System.out.println("Server: packet sent");
// We're finished, so close the sockets.
sendSocket.close();
receiveSocket.close();
}
public static void main( String args[] ) throws UnknownHostException
{
while(true) {
SimpleEchoServer c = new SimpleEchoServer();
c.receiveAndEcho();
}
}
}
Now this code works if I were to only send one packet to the host, which sends to the server which returns another packet to the client from the host. However when I try to send more than one packet I get an error. To send more than one packet I basically create a loop in the main that simply calls the methods 11 times and i place a while loop in the server and host to have it running continuously in order to wait for packets. To see it run once, just eliminate the while loops in the main function of all three classes.
Any help as to how I can fix this error is greatly appreciated! Thanks!
On each call to the SimpleEchoClient c = new SimpleEchoClient();, your code tries to create a client on port 5000. Since you already have a client running on the same port, the exception is thrown.
So do it only once and send the packet 11 times.
public static void main(String args[])
{
boolean checkRead = true;
int count =0;
SimpleEchoClient c = new SimpleEchoClient();
for(int i = 0; i<=10; i++) {
System.out.println("Count:" + count);
c.sendAndReceive(checkRead);
}
}
Check how I have changed the loop condition to <=10 to make sure that 11 packets are sent.
I think the problem is that client 2 is not entering receiving mode and the connection between clients closes before first client sends something to the second... but I might be wrong.
Here is the code of server and clients. Program is based on token ring algorithm. I'm not fluent in Java so I suppose I didn't use the best way to solve it.
Server:
public class TokenServer
{
ServerSocket clientConn;
public TokenServer(int port){
System.out.println("Server connecting to port "+port);
try {
clientConn = new ServerSocket(port);
}
catch (Exception e) {
System.out.println("Exception:"+e);
System.exit(1);
}
}
public static void main(String[] args) {
int port = 8000;
if (args.length > 0) {
try {
port = Integer.parseInt(args[0]);
}
catch (Exception e) {
port = 8000;
}
}
TokenServer server = new TokenServer(port);
System.out.println("Server running on port "+port);
server.listen();
}
public void listen(){
try{
System.out.println("Waiting for clients...");
while(true) {
Socket clientReq = clientConn.accept();
System.out.println("Connection from "+clientReq.getInetAddress().getHostName());
serviceClient(clientReq);
}
}
catch (IOException e) {
System.out.println("Exception:"+e);
}
}
public void serviceClient(Socket s){
System.out.println("New request from "+s.getInetAddress());
ObjectInputStream inStream = null;
ObjectOutputStream outStream = null;
int message_id;
Object message = null;
try{
outStream = new ObjectOutputStream(s.getOutputStream());
inStream = new ObjectInputStream(s.getInputStream());
message_id = inStream.readInt();
System.out.println("Got message "+message_id);
int zmienna;
zmienna = message_id + message_id;
outStream.writeObject(zmienna);
outStream.flush();
}
catch (Exception e) {
System.out.println("Exception:"+e);
}
System.out.println("Done.");
}
}
Client 1:
public class TokenClient1{
int sendport,recport;
boolean hasToken = true;
boolean setSendData = false;
String host;
public TokenClient1(String host){
this.host = host;
}
void setSendPort(int sendport)
{
this.sendport = sendport;
}
void setRecPort(int recport)
{
this.recport = recport;
}
public Object sendMessage(int message_id) throws Exception
{
Socket serverConn;
ObjectInputStream inStream = null;
ObjectOutputStream outStream = null;
Object response = null;
serverConn = new Socket(host, sendport);
outStream = new ObjectOutputStream(serverConn.getOutputStream());
inStream = new ObjectInputStream(serverConn.getInputStream());
outStream.writeInt(message_id);
outStream.flush();
response = inStream.readObject();
serverConn.close();
//hasToken = false;
return response;
}
public Object recData() throws Exception
{
Socket serverConn;
ObjectInputStream inStream = null;
Object response = null;
serverConn = new Socket(host, recport);
inStream = new ObjectInputStream(serverConn.getInputStream());
response = inStream.readObject();
serverConn.close();
if(response.toString().equals("Token"))
{
hasToken = true;
}
return response;
}
public static void main (String[] args){
TokenClient1 client = new TokenClient1("localhost");
TokenClient1 server = new TokenClient1("localhost");
client.setSendPort(8002);
client.setRecPort(8002);
server.setSendPort(8000);
Scanner scan = new Scanner(System.in);
int wybor, zmienna;
try{
while(true)
{
if(client.hasToken == true){
System.out.println("Do you want to enter the Data --> \n1. YES \n0. NO");
wybor = scan.nextInt();
switch (wybor) {
case 1:
{
System.out.println("ready to send \n Podaj liczbe do dodania: ");
//server.setSendData = true;
zmienna = scan.nextInt();
System.out.println("odpowiedz servera:");
System.out.println((Integer)server.sendMessage(zmienna));
break;
}
case 0:
{
System.out.println("i m in else");
client.sendMessage(0);
client.recData();
System.out.println("i m leaving else");
break;
}
}
}
else {
System.out.println("ENTERING RECEIVING MODE...");
client.recData();
}
}
}
catch(Exception e) {
System.out.println("Esception:"+e);
}
}
}
Client 2:
public class TokenClient2
{
int sendport,recport;
boolean hasToken = false;
String host;
ServerSocket clientConn;
public TokenClient2(String host){
this.host = host;
}
void setSendPort(int sendport)
{
this.sendport = sendport;
}
void setRecPort(int recport)
{
this.recport = recport;
}
public Object sendMessage(int message_id) throws Exception
{
Socket serverConn;
ObjectInputStream inStream = null;
ObjectOutputStream outStream = null;
Object response = null;
serverConn = new Socket(host, sendport);
outStream = new ObjectOutputStream(serverConn.getOutputStream());
inStream = new ObjectInputStream(serverConn.getInputStream());
outStream.writeInt(message_id);
outStream.flush();
response = inStream.readObject();
serverConn.close();
//hasToken = false;
return response;
}
void recData() throws Exception
{
try{
System.out.println("Waiting for clients...");
// while(true) {
Socket serverConn;
ObjectInputStream inStream = null;
Object response = null;
clientConn = new ServerSocket(8002);
serverConn = new Socket(host, 8000);
Socket clientReq = clientConn.accept();
System.out.println("Connection from "+clientReq.getInetAddress().getHostName());
inStream = new ObjectInputStream(serverConn.getInputStream());
response = inStream.readObject();
clientConn.close();
System.out.println("Waiting for cents...");
if(response.equals(0))
{
System.out.println("tdfss...");
hasToken = true;
}
//return response;
}
//}
catch (IOException e) {
System.out.println("Exception:"+e);
}
}
public static void main (String[] args){
TokenClient2 client = new TokenClient2("localhost");
TokenClient2 server = new TokenClient2("localhost");
client.setSendPort(8002);
client.setRecPort(8002);
server.setSendPort(8000);
Scanner scan = new Scanner(System.in);
int wybor, zmienna;
try{
while(true)
{
if(client.hasToken == true){
System.out.println("Do you want to enter the Data --> \n1. YES \n0. NO");
wybor = scan.nextInt();
switch (wybor) {
case 1:
{
System.out.println("ready to send \n Podaj liczbe do dodania: ");
//server.setSendData = true;
zmienna = scan.nextInt();
System.out.println("odpowiedz servera:");
System.out.println((Integer)server.sendMessage(zmienna));
break;
}
case 0:
{
System.out.println("i m in else");
client.sendMessage(0);
client.recData();
System.out.println("i m leaving else");
break;
}
}
}
else {
client.hasToken=true;
System.out.println("ENTERING RECEIVING MODE...");
client.recData();
}
}
}
catch(Exception e) {
System.out.println("Esception:"+e);
}
}
}
am making a simple ftp client/server program which on command from the clients lists files, tells the current directory, downloads files.
I want to create a server which is able to be connect with multiple clients and is capable of handling multiple commands at a time. I have used threading but my code gives the following error after the 1st command is executed.
socket closed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.DataInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at Myserver$Connecthandle.run(Myserver.java:123)
at Myserver.main(Myserver.java:35)
java.net.SocketException: socket closed
Here's my server code:
public class Myserver {
static final int PortNumber = 120;
static ServerSocket MyService;
static Socket clientSocket = null;
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
File directory;
directory = new File(System.getProperty("user.dir"));
try {
MyService = new ServerSocket(PortNumber);
String cd = directory.toString();
System.out.println(cd);
System.out.println("Listening on " + PortNumber);
while(true) {
clientSocket = MyService.accept();
Connecthandle a = new Connecthandle(clientSocket, directory);
a.start();
}
}
catch (IOException e) {
System.out.println(e);
}
}
static class Connecthandle extends Thread {
File Directory;
Socket clientsocket;
PrintWriter outgoing;
// Constructor for class
Connecthandle(Socket clients, File dir) {
clientsocket = clients;
Directory = dir;
}
// Works Fine
void listfiles() throws IOException {
String []Listfile = Directory.list();
String send = "";
for (int j = 0; j < Listfile.length; j++) {
send = send + Listfile[j] + ",";
}
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
GoingOut.writeBytes(send);
GoingOut.flush();
// GoingOut.close();
}
// Works Fine
void currentdirectory() throws IOException {
String cd = Directory.toString();
String cdd = "resp," + cd;
System.out.println(cdd);
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
GoingOut.writeBytes(cdd);
GoingOut.flush();
GoingOut.close();
}
// Works fine
void sendfiles(String fileName) {
try {
File nfile = new File(fileName);
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
if ( (! nfile.exists()) || nfile.isDirectory() ) {
GoingOut.writeBytes("file not present");
} else {
BufferedReader br = new BufferedReader(new FileReader(nfile));
int coun = 0;
String lin;
while ((lin = br.readLine()) != null) {
coun++;
}
GoingOut.writeBytes("resp," + fileName + "," + String.valueOf(coun) + "\n");
#SuppressWarnings("resource")
BufferedReader sr = new BufferedReader(new FileReader(nfile));
String line;
while ((line = sr.readLine()) != null) {
GoingOut.writeBytes(line+"\n");
GoingOut.flush();
}
GoingOut.close();
br.close();
}
} catch (IOException e) {
System.out.println("Unable to send!");
}
}
public void start() {
DataInputStream comingin = null;
try {
comingin = new DataInputStream(clientsocket.getInputStream());
} catch (IOException e2) {
e2.printStackTrace();
}
InputStreamReader isr = null;
try {
isr = new InputStreamReader(comingin, "UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
BufferedReader br = new BufferedReader(isr);
while (true) {
try {
String message = br.readLine();
if (message.contains("pwd")) {
currentdirectory();
} else if (message.contains("list")) {
listfiles();
} else if (message.contains("get")) {
String fileName = new String(message.substring(8, message.length()));
sendfiles(fileName);
} else if (message.contains("exit")) {
System.exit(0);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
clientsocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
I moved all the methods into start() so i only needed to declare dataoutputstream once but now it gives a NULLPOINTEREXCEPTION whenever i use Outgoing.writeBytes
Updated:
static class Connecthandle extends Thread {
File Directory;
Socket clientsocket;
PrintWriter outgoing;
// Constructor for class
Connecthandle(Socket clients, File dir) {
clientsocket = clients;
Directory = dir;
}
public void run() {
DataInputStream comingin = null;
try {
comingin = new DataInputStream(clientsocket.getInputStream());
} catch (IOException e2) {
e2.printStackTrace();
}
InputStreamReader isr = null;
try {
isr = new InputStreamReader(comingin, "UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
BufferedReader br = new BufferedReader(isr);
while (true) {
try {
String message = br.readLine();
if (message.contains("pwd")) {
String cd = Directory.toString();
String cdd = "resp," + cd;
System.out.println(cdd);
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
GoingOut.writeBytes(cdd);
GoingOut.flush();
} else if (message.contains("list")) {
String []Listfile = Directory.list();
String send = "";
for (int j = 0; j < Listfile.length; j++) {
send = send + Listfile[j] + ",";
}
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
GoingOut.writeBytes(send);
GoingOut.flush();
} else if (message.contains("get")) {
String fileName = new String(message.substring(8, message.length()));
try {
File nfile = new File(fileName);
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
if ( (! nfile.exists()) || nfile.isDirectory() ) {
GoingOut.writeBytes("file not present");
} else {
BufferedReader wr = new BufferedReader(new FileReader(nfile));
int coun = 0;
String lin;
while ((lin = wr.readLine()) != null) {
coun++;
}
GoingOut.writeBytes("resp," + fileName + "," + String.valueOf(coun) + "\n");
#SuppressWarnings("resource")
BufferedReader sr = new BufferedReader(new FileReader(nfile));
String line;
while ((line = sr.readLine()) != null) {
GoingOut.writeBytes(line+"\n");
GoingOut.flush();
}
GoingOut.close();
br.close();
}
} catch (IOException e) {
System.out.println("Unable to send!");
}
} else if (message.contains("exit")) {
System.exit(0);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
clientsocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
Closing the input stream or output stream of a socket closes the other stream and the socket. I don't see why you need to close anything here until the client disconnects or you time him out.
In my android app, I am sending messages via UDP. I followed this and this.
However, I am not able to send the initial packet from the client to the server. Please let me know if I am doing something wrong in my code below:
class serverCommunicationThread implements Runnable
{
public void run()
{
try {
serverSocket = new DatagramSocket(STATICPORT);
ServerReceiveMessageThread rcvMsgThread = new ServerReceiveMessageThread(serverSocket);
new Thread(rcvMsgThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
This is the ServerReceiveMessageThread class:
class ServerReceiveMessageThread implements Runnable
{
DatagramSocket clientSocket;
byte[] buffer = new byte[108];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
ServerReceiveMessageThread(DatagramSocket clientSocket)
{
this.clientSocket = clientSocket;
}
#Override
public void run()
{
int counter = 0;
MsgStruct recvMsgStruct = null;
try {
ByteArrayOutputStream baosServer = new ByteArrayOutputStream();
serializeServer = new ObjectOutputStream(baosServer);
clientSocket.receive(packet);
ByteArrayInputStream baosRecv = new ByteArrayInputStream(buffer);
deserializeServer = new ObjectInputStream(baosRecv);
while(true)
{
try {
recvMsgStruct = (MsgStruct) deserializeServer.readObject();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
boolean retVal = serverSendMessage(clientSocket, recvMsgStruct, baosServer.toByteArray());
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
The serverSendMessage method:
public boolean serverSendMessage(DatagramSocket clientSocket, MsgStruct msgStruct, byte[] buf)
{
MsgStruct recvMsgStruct = new MsgStruct();
recvMsgStruct.pingPong = true;
recvMsgStruct.msgId = msgStruct.msgId;
recvMsgStruct.bufferMsg = msgStruct.bufferMsg;
try {
serializeServer.writeObject(recvMsgStruct);
serializeServer.flush();
DatagramPacket packet = new DatagramPacket(buf, buf.length, InetAddress.getByName(mobileIP), STATICPORT);
clientSocket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
The code for the client send/receive is similar to that of the server. I get a NullPointerException here.
serializeClient.writeObject(mobileSendMsgStruct);
public boolean mobileSendMessage(int msgId)
{
MsgStruct mobileSendMsgStruct = new MsgStruct();
mobileSendMsgStruct.bufferMsg = new byte[100];
mobileSendMsgStruct.pingPong = false;
mobileSendMsgStruct.msgId = msgId;
rand.nextBytes(mobileSendMsgStruct.bufferMsg);
try {
sendTime = System.nanoTime();
serializeClient.writeObject(mobileSendMsgStruct); /*I get a NullPointerException here*/
serializeClient.flush();
byte[] sendBuf = baosSend.toByteArray();
DatagramPacket packet = new DatagramPacket(sendBuf, sendBuf.length, InetAddress.getByName(staticIP), STATICPORT);
mobileSocket.send(packet);
outPing.write(Long.toString(sendTime) + ", " + String.valueOf(mobileSendMsgStruct.msgId) + ", " + String.valueOf(mobileSendMsgStruct.bufferMsg) + " | ");
} catch (IOException e1) {
e1.printStackTrace();
return false;
}
return true;
}
I have Socket- Client application. The code below is supposed to allow client to both read replies from server and read input at the same time. The thing is- this code "works" while debugging in eclipse, as in I recieve messages outside of normal flow in a process I'm debugging, but If i launch application normally, it completly ignores that proces? What is the most common cause of "IDE working, real life not" syndrome?
Whole files:
Server:
public class Server implements Runnable {
static ServerSocket serverSocket;
Socket tempSocket;
Socket tempSocket2;
static volatile List<User> usersList = new ArrayList<User>();
static boolean waitForNew = true;
PrintWriter tempOut;
volatile User[] tempUser;
volatile boolean isReadingN = false;
public Server(Socket _s, Socket _s2) {
tempSocket = _s;
tempSocket2 = _s2;
}
public Server(PrintWriter nOut, User[] user) {
tempOut = nOut;
tempUser = user;
isReadingN = true;
}
#Override
public void run() {
if (isReadingN) {
while (true) {
if (tempUser != null && tempUser.length > 0
&& tempUser[0] != null)
break;
}
User[] myUser = new User[1];
myUser[0] = tempUser[0];
// myUser[0]=usersList.
while (true) {
if (myUser[0].isCurrentlyLoggedIn() == false)
break;
String[] toSend = null;
if (myUser[0].isNotificable())
toSend = myUser[0].printNotifications().split("\n");
else
continue;
//tempOut.println("");
int sendL=toSend.length;
tempOut.println(String.valueOf(sendL));
for (int i = 0; i < toSend.length; i++)
tempOut.println(toSend[i]);
}
return;
}
Socket clientSocket = tempSocket;
System.out.println("Initiating conversation with the client");
String inputLine;
try {
System.out.print("creating server out...");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
Socket iClientSocket = tempSocket2;
ObjectOutputStream iout = new ObjectOutputStream(
iClientSocket.getOutputStream());
System.out.println("OK!");
System.out.print("creating server in...");
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
System.out.println("OK!");
System.out.print("creating server image streams...");
System.out.println("OK!");
System.out.println("Server initiating conversation");
User[] currentUser = new User[1];
new Thread(new Server(out, currentUser)).start();
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
boolean[] downloadPicture = new boolean[1];
downloadPicture[0] = false;
String input = Command.call(inputLine, currentUser, usersList,
downloadPicture);
String[] toSend;
if (input != null) {
toSend = input.split("\n");
} else
toSend = new String[0];
out.println(String.valueOf(toSend.length));
for (int i = 0; i < toSend.length; i++)
out.println(toSend[i]);
if (downloadPicture[0]) {
System.out.println("File sent.");
iin.close();
} else{
out.println("1");
out.println("Error: File does not exit.");}
} else
//out.println(" ");
if (inputLine.equals("EXIT")) {
waitForNew = false;
break;
}
}
// End communication graciously
System.out.println("Closing sockets, closing streams");
out.close();
in.close();
clientSocket.close();
serverSocket.close();
} catch (IIOException e) {
System.out.println("Error: Could not find file");
e.printStackTrace();
System.exit(-1);
} catch (IOException e) {
System.out.println("Error");
e.printStackTrace();
System.exit(-1);
}
}
public static void main(String[] args) {
// Create socket on port given in argument, localhost
if (args.length == 0) {
System.out
.println("Not enough arguments. Try Server <port number>");
System.exit(-1);
}
int port = 0;
try {
port = Integer.valueOf(args[0]);
System.out.println("Application start");
serverSocket = new ServerSocket(port);
System.out.println("Created socket on port " + port);
} catch (NumberFormatException c) {
System.out
.println("Incorrect port number. Try Server <port number>");
System.exit(-1);
} catch (IOException e) {
System.exit(-1);
}
// Waiting for client
System.out.println("Waiting for client...");
Socket clientSocket = null;
Socket iClientSocket = null;
while (waitForNew) {
try {
clientSocket = serverSocket.accept();
iClientSocket = serverSocket.accept();
new Thread(new Server(clientSocket, iClientSocket)).start();
} catch (IOException e) {
System.out.println("Accept failed: " + port);
System.exit(-1);
}
}
}
}
Client:
public class Client implements Runnable {
static Socket clientSocket = null;
static Socket iClientSocket = null;
static PrintWriter out = null;
static BufferedReader in = null;
static InputStream iin = null;
public static void main(String[] args) {
int port = Integer.valueOf(args[1]);
String host = args[0];
try {
clientSocket = new Socket(host, port);
iClientSocket = new Socket(host, port);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
iin = iClientSocket.getInputStream();
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + host);
System.exit(-1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for " + "the connection to: "
+ host);
System.exit(-1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(
System.in));
String userInput;
try {
new Thread(new Client()).start();
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
}
System.out.println("Closing sockets, closing streams");
out.close();
in.close();
stdIn.close();
iClientSocket.close();
clientSocket.close();
} catch (IOException e) {
System.exit(-1);
}
}
#Override
public void run() {
String a = null;
try {
while (true) {
if((a = in.readLine()) == null)
continue;
int n;
try{
n = Integer.valueOf(a);
}catch(NumberFormatException e){
System.out.println(a);
n=1;
//continue;
}
a = "";
for (int i = 0; i < n; i++)
a += in.readLine() + "\n";
System.out.println(a);
// if(a.contains("POST"),)
if (a.compareToIgnoreCase("EXIT") == 0) {
System.out.println("Exiting");
break;
}
if (a.endsWith("Sending File\n")) {
System.out.println("Recieving image.");
(some unimportant for now code)
System.out.println("Image recieved");
}
}
} catch (IOException e) {
}
}
}