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);
}
}
}
Related
It's my first time working with sockets, in order to get a better understanding of what's going on I decided to build a client server chat application which can support several users.
At first, I used DataInputStream / DataOutputStream to communicate and everything works well. But I would like to switch to an ObjectStream and that's where the problem occurs. Once I replace all the DataInputStream / DataOutputStream by ObjectInputStream / ObjectOutputStream, I'm no longer able to print the retrieved data.
This is the code that I used before, which works (DataStream) :
SERVER:
try {
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeUTF("HI FROM SERVER");
while (!socket.isClosed()) {
try {
if (in.available() > 0) {
String input = in.readUTF();
for (ClientThread thatClient : server.getClients()){
DataOutputStream outputParticularClient = new DataOutputStream(thatClient.getSocket().getOutputStream());
outputParticularClient.writeUTF(input + " GOT FROM SERVER");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
CLIENT:
try {
socket = new Socket("localhost", portNumber);
DataInputStream in = new DataInputStream(socket.getInputStream());
new Thread(()->{
while(!socket.isClosed()){
try {
if (in.available() > 0){
String input = in.readUTF();
System.out.println(getUserName() + " > " + input);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
And this is how I tried to perform the same idea with ObjectStream :
SERVER:
try {
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
while (!socket.isClosed()) {
try {
if (in.available() > 0) {
Message input;
try {
input = (Message)in.readObject();
if (input.equals(null)){
System.err.println("SERVER RETRIEVED NULL OBJECT");
}
for (ClientThread thatClient : server.getClients()){
ObjectOutputStream outputParticularClient = new ObjectOutputStream(thatClient.getSocket().getOutputStream());
outputParticularClient.writeObject(input);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
CLIENT:
try {
socket = new Socket(getHost(), portNumber);
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
new Thread(()->{
while(!socket.isClosed()){
try {
if (in.available() > 0){
Message input = null;
try {
input = (Message)in.readObject();
if (input.equals(null)){
System.err.println("CLIENT RETRIEVED NULL OBJECT");
}
System.out.println("CLIENT " + input.toString());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
I feel like it has something to do with this if statement if (in.available() > 0) but I cannot say precisely what's going on.
available() doesn't do what you may think it does and it is almost never useful in production code (and that's particularly true for ObjectInputStream). The reason you don't receive any data is in fact that in.available() always returns 0 as you already suspected.
As noted in the comments, the StreamCorruptedException is caused by writing to an existing ObjectInputStream that has already been written to using another instance of ObjectOutputStream. Cf. the answer StreamCorruptedException: invalid type code: AC for further explanation.
Here is some quick & dirty example code that has a server echoing the messages from two clients. It's not clean but it may give you an idea how to approach your problem:
public class SO56493162 {
private static final class Message implements Serializable {
private static final long serialVersionUID = 1L;
private static int cnt = 0;
private final int id;
public Message(int id) {
++cnt;
this.id = id;
}
public String toString() {
return "Msg from " + id + " : " + cnt;
}
}
private static final class Client implements Runnable {
private InetSocketAddress addr = null;
private int id = -1;
Client(InetSocketAddress addr, int id) {
this.addr = addr;
this.id = id;
}
public void run() {
int timeout = 3000;
Socket s = null;
try {
s = new Socket();
s.connect(addr, timeout);
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
System.out.println("Client " + id + " connected");
while (true) {
Thread.sleep(new Random().nextInt(2000));
Message hello = new Message(id);
oos.writeObject(hello);
oos.flush();
Message reply = (Message) ois.readObject();
System.out.println("Reply: " + reply.toString());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
s.close();
} catch (Exception ignore) {
}
}
}
}
private static final class Server implements Runnable {
private ServerSocket sock = null;
Server(ServerSocket sock) throws IOException {
this.sock = sock;
}
public void run() {
System.out.println("starting server");
try {
while (true) {
final Socket client = sock.accept();
System.out.println("connection accepted");
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
ObjectInputStream ois = new ObjectInputStream(client.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
while (!client.isClosed()) {
try {
Message input = (Message) ois.readObject();
oos.writeObject(input);
oos.flush();
} catch (EOFException eof) {
System.err.println("EOF!");
client.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.setDaemon(true);
t.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String args[]) throws IOException, InterruptedException {
final int port = 9876;
Thread ts = new Thread(new Runnable() {
#Override
public void run() {
try {
new Server(new ServerSocket(port)).run();
} catch (Exception e) {
e.printStackTrace();
}
}
});
ts.setDaemon(true);
ts.start();
InetSocketAddress addr = new InetSocketAddress("localhost", port);
for (int i = 0; i < 2; ++i) {
Client cl = new Client(addr, i);
Thread tc = new Thread(cl);
tc.setDaemon(true);
tc.start();
}
Thread.sleep(10000);
System.err.println("done");
}
}
I'm trying to learn how to use java sockets before next semester. I wrote this program that is supposed to accept accept a message from a sender and send the message to a reciever. You specify the reciever by writing the name of the client that is connected, if the client isn't connected then the server will respond by sending the message "DISCONNECTED". But for some reason the message isn't sent to the reciever. I can still send the message to the sender though. Is this the right forum to ask for this kind of help?
This is my client class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class MyTestClient {
static int port = 0;
static String ip = "";
static String name = "";
public static void main(String args[] ) {
if(args.length == 3) {
try{
port = Integer.parseInt(args[1]);
} catch(NumberFormatException e) {
System.out.println("Usage: Java MyTestClient <ip> <port> <name>");
System.exit(0);
}
ip = args[0];
name = args[2];
} else {
System.out.println("Usage: Java MyTestClient <ip> <port> <name>");
System.exit(0);
}
try {
Socket socket = new Socket(ip, port);
new Thread(new MessageHandler(socket)).start();
new Thread(new InputHandler(socket)).start();
} catch (IOException e) {
System.out.println("Could not connect to: " + ip + " : " + port);
System.exit(0);
}
}
public static class MessageHandler implements Runnable {
Socket socket;
public MessageHandler(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
PrintWriter out = null;
BufferedReader in = null;
try {
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}catch(IOException e) {
e.printStackTrace();
}
String fromServer;
try {
while ((fromServer = in.readLine()) != null) {
System.out.println(fromServer);
fromServer.trim();
if(fromServer.contains(" ")) {
String split[] = fromServer.split(" ", 2);
System.out.println(split.length == 2 ? split[1] + " Is a two part message" : "Strange message");
} else {
if(fromServer.equals("NAME")) {
System.out.println("Server asks for name | gives given name to server");
out.println(name);
}
if(fromServer.equals("SUCCESS")) {
System.out.println("Message succesfully sent");
}
if(fromServer.equals("ERROR")) {
System.out.println("Something went wrong when sending the message");
}
if(fromServer.equals("OCCUPIED")) {
System.out.println("Name was already used. Start the program with another name");
socket.close();
System.exit(0);
}
if(fromServer.equals("DISCONNECTED")) {
System.out.println("The reciever was not connected");
}
if(fromServer.equals("REGISTERED")) {
System.out.println("Successfully logged in to server");
}
}
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
public static class InputHandler implements Runnable {
Socket socket;
public InputHandler(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
String fromUser = null;
PrintWriter out = null;
try {
out = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader kbi = new BufferedReader(new InputStreamReader(System.in));
try {
while ((fromUser = kbi.readLine()) != null) {
out.println(fromUser);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
This is my server class
import java.io.*;
import java.net.*;
import java.util.*;
public class MyServer {
public static int port;
public static int maxConnections;
public static final String NAME = "Server";
private static Map<String, Socket> socketsMap = new HashMap<>();
public static void main(String args[]) {
if(args.length == 2) {
try{
port = Integer.parseInt(args[0]);
maxConnections = Integer.parseInt(args[1]);
}catch(Exception e){
System.out.println("Usage: Java Myserver <port> <maxConnections>");
System.exit(0);
}
} else {
System.out.println("Usage: Java Myserver <port> <maxConnections>");
System.exit(0);
}
new Thread(new ConnectionHandler(port, maxConnections)).start();
}
public static class ConnectionHandler implements Runnable {
private ServerSocket server;
private Socket socket = null;
public int currentSocket = 0;
public int port = 0;
public int maxConnections = 0;
public ConnectionHandler(int port, int maxConnections) {
this.maxConnections = maxConnections;
this.port = port;
}
#Override
public void run() {
try {
server = new ServerSocket(7777);
} catch (IOException e1) {
System.out.println("Server could not connect to port: " + port);
e1.printStackTrace();
System.exit(0);
}
while(currentSocket++ < maxConnections) {
try {
socket = server.accept();
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println("NAME");
String message;
while((message = in.readLine()) != null) {
if(!socketsMap.containsKey(message) || message.equals("SERVER")) {
out.println("REGISTERED");
socketsMap.put(message, socket);
System.out.println(message + " has logged on server");
new Thread(new SocketHandler(socketsMap.get(message))).start();
} else {
out.println("OCCUPIED");
System.out.println(socket.getInetAddress().toString() + " has tried to login with existing name " + message);
socket.close();
currentSocket--;
}
socket = null;
break;
}
} catch (IOException e) {
System.out.println("Something went wrong with client connection");
}
}
}
}
public static class SocketHandler implements Runnable {
Socket socket = null;
public SocketHandler(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter respond = new PrintWriter(socket.getOutputStream(), true);
String input;
while((input = in.readLine() ) != null) {
String[] info = input.split(" ", 2);
if(info.length != 2){
System.out.println("Message computed wrong");
respond.println("ERROR");
break;
}
if(info[0].equals("SERVER")) {
//TODO: Write a server command handler class
} else if ( socketsMap.containsKey(info[0]) ){
Socket reciever = socketsMap.get(info[0]);
PrintWriter out = new PrintWriter(reciever.getOutputStream());
respond.println("SUCCESS");
System.out.println(info[0] + " send the message: "+ info[1]);
out.println("MESSAGE" + " " + info[1]);
break;
} else {
System.out.println("Reciever is not connected");
respond.println("DISCONNECTED");
}
}
}catch(IOException e) {
e.printStackTrace();
}
}
}
}
Maybe you can run it on your computers and see what i mean?
#Override
public void run() {
try {
server = new ServerSocket(7777);
} catch (IOException e1) {
System.out.println("Server could not connect to port: " + port);
e1.printStackTrace();
System.exit(0);
}
change the code above to
#Override
public void run() {
try {
server = new ServerSocket(port);
} catch (IOException e1) {
System.out.println("Server could not connect to port: " + port);
e1.printStackTrace();
System.exit(0);
}
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.
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) {
}
}
}