Java: Multi line output via Socket - java

i got some struggle with my code. I have to send some commands via client to a server (create a file or list files in the directory) the server should create the files or send a list of existing files back to the client. It worked, but i guess the while loop for output on client side never stops and the client cant input new commands. I dont get the problem :(. Many thanks in advance.
Server:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Arrays;
import java.io.File;
import java.io.FileWriter;
public class MyServer {
private final static String DIRECTORYLISTING = "directoryListing";
private final static String ADDFILE = "addFile";
private static String path = "/home/christoph/eclipse-workspace/Distributed Systems Ex 01/Work_Folder";
private static PrintWriter pw = null;
private static File file = null;
private static String command1 = null; // Command
private static String command2 = null; // File name
private static String command3 = null; // File content
private static ArrayList<File> files = new ArrayList<>(); //
public static void splitClientInput(String clientInput) {
try {
String [] splittedInput = clientInput.split(";");
command1=splittedInput[0];
command2=splittedInput[1];
command3=splittedInput[2];
} catch(ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
}
public static void directoryListing() {
try {
File[] s = file.listFiles();
for(int i = 0; i<s.length;i++) {
pw.println(s[i].getName());
}
pw.flush();
}catch(NullPointerException e) {
e.printStackTrace();
}
}
public static void addFile(String command2,String command3) throws IOException {
file = new File(path +"/" +command2);
if(file.isFile()) {
pw.println("This Filename "+command2+" already exists.");
} else {
try {
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(command3);
files.add(file);
pw.println(file.getName()+" created");
if(command3.equals(null)) {
pw.println("Your created file is empty");
}
fileWriter.close();
}catch(IOException e) {
pw.println("Error by creating file");
}catch (NullPointerException e) {
pw.println("Your created file is empty");
}
}
}
public static void checkInputCommand(String command1, String command2, String command3) throws IOException {
switch(command1) {
case DIRECTORYLISTING:
directoryListing();
break;
case ADDFILE:
addFile(command2, command3);
break;
}
}
public static void main(String[] args) {
try {
file = new File(path);
files = new ArrayList<File>(Arrays.asList(file.listFiles()));
ServerSocket ss = new ServerSocket(1118);
System.out.println("Server Started...");
Socket socket = ss.accept();
OutputStream os = socket.getOutputStream();
pw=new PrintWriter(os);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String clientInput = null;
while((clientInput = br.readLine()) != null) {
splitClientInput(clientInput);
checkInputCommand(command1, command2, command3);
pw.flush();
}
pw.flush();
br.close();
isr.close();
is.close();
pw.close();
os.close();
socket.close();
ss.close();
System.out.println("Server closed");
}catch(BindException e) {
e.printStackTrace();
}catch(SocketException e) {
e.printStackTrace();
}catch(java.lang.NullPointerException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
}
Client:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class MyClient {
public static void main(String[] args) throws Exception{
try {
Scanner sc = new Scanner(System.in);
Socket s = new Socket("127.0.0.1", 1118);
System.out.println("Client started");
InputStream is = s.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
OutputStream os = s.getOutputStream();
PrintWriter pw = new PrintWriter(os);
String str= null;
while(true){
System.out.print("Client input: ");
pw.println(sc.nextLine());
pw.flush();
// System.out.println(br.readLine());
/*
* dont get out of the loop?
*/
while((str=br.readLine())!=null) {
System.out.println(str);
}
br.close();
isr.close();
is.close();
s.close();
}
} catch(NullPointerException e) {
e.printStackTrace();
} catch(ConnectException e) {
e.printStackTrace();
}catch(UnknownHostException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
}

Related

Exception in readObject of String

I'm trying to read a text file from the server string by string (line by line from the file).
It works good until readObject in the client side has nothing to read and than I get exception and going to "client error".
I have tried to close streams and sockets, ask questions and also I have tried to use scanner but none of the options above helped me.
Can u help me?
client side:
package hit.model;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class MMUClient {
private ArrayList<String> userDetails;
private String fileFromServer =null;
private ObjectOutputStream outToServer;
private ObjectInputStream inFromServer;
private String fileName;
private boolean ERROR = true;
private String messageError = "No Errors";
private PrintWriter printerWriter;
public MMUClient(ArrayList<String> userParameters){
userDetails = userParameters;
};
public MMUClient(String filePath){
fileName = filePath;
};
public ArrayList<String> getUserDetails() {
return userDetails;
}
public void setUserDetails(ArrayList<String> userDetails) {
this.userDetails = userDetails;
clientAuthenticate();
}
public void clientAuthenticate(){
try{
Socket myServer = null;
try {
//1. creating a socket to connect to the server
myServer = new Socket("localhost", 12345);
System.out.println("Connected to localhost in port 12345");
//2. get Input and Output streams
outToServer = new ObjectOutputStream(myServer.getOutputStream());
inFromServer=new ObjectInputStream(myServer.getInputStream());
//3: Communicating with the server
outToServer.writeObject(userDetails);
//4. get server answer
fileFromServer = (String) inFromServer.readObject();
printerWriter = new PrintWriter("logClient.txt");
if(fileFromServer.contains("Error")){
messageError = "Error";
ERROR = true;
}
else{
if (fileFromServer.contains("Wrong")){
messageError = "Wrong";
ERROR = true;
}
else
while(fileFromServer != null){
// messageError = "No Errors";
// ERROR = false;
System.out.println(fileFromServer);
printerWriter.println(fileFromServer);
// writeData(fileFromServer);
fileFromServer = (String) inFromServer.readObject();
}
printerWriter.close();
}
} catch (IOException e) {
System.out.println("Client error");
}finally{
inFromServer.close();
outToServer.close();
myServer.close();
}
}catch (Exception e) {
System.out.println("Client error Details");
}
}
//**********************write into text file from server***************************
/* private void writeData(String lineToWrite) {
FileWriter fileWriter = null;
String filetowrite = "logClient.txt";
try {
PrintWriter printerWriter = new PrintWriter(filetowrite);
printerWriter.println(lineToWrite);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
*/
//************************if there is any error with the client******************************
public boolean getError(){
return ERROR;
}
public String getMessageError() {
return messageError;
}
public void setMessageError(String messageError) {
this.messageError = messageError;
}
}
server side:
package hit.applicationservice;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
import hit.login.AuthenticationManager;
public class MMULogFileApplicationService implements Runnable {
//MMULogService logService;
AuthenticationManager authenticateDetails;
MMULogFileBrowsing browsing;
ArrayList<String> userDetails;
private Socket someClient = null;
private ObjectOutputStream outToClient;
private ObjectInputStream inFromClient;
String filePath = "/Users/oferg/Desktop/lastVirsion/MMUProject/log.txt";
public MMULogFileApplicationService (Socket socket ){
someClient = socket;
};
#Override
public void run() {
//3. get Input and Output streams
try{
outToClient = new ObjectOutputStream(someClient.getOutputStream());
inFromClient = new ObjectInputStream(someClient.getInputStream());
userDetails = (ArrayList<String>) inFromClient.readObject();
System.out.println("Connection successful ");
}catch(IOException | ClassNotFoundException ioException){
ioException.printStackTrace();
}
boolean userFound = false;
try {
authenticateDetails = new AuthenticationManager();
userFound = authenticateDetails.authenticate(userDetails.get(0), userDetails.get(1));
if(userFound)
{
browsing = new MMULogFileBrowsing(someClient, userDetails.get(2), filePath);
if(!browsing.searchIfFileExist()){
//write object to Socket
String sendMessage = "Wrong FileName the file isn't found";
outToClient.writeObject(sendMessage);
}
else{
getFileToClient();
}
}
else
{
//write object to Socket
String sendMessage = "Error - the user isn't exist";
outToClient.writeObject(sendMessage);
}
} catch (ClassNotFoundException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
inFromClient.close();
outToClient.close();
someClient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void getFileToClient() throws IOException {
FileReader fileReader = null;
String currentLine = null;
try {
fileReader = new FileReader(filePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((currentLine = bufferedReader.readLine())!= null){
if (currentLine.isEmpty() == false ){
outToClient.writeObject(currentLine);
outToClient.flush();
}
}
outToClient.close();
bufferedReader.close();
fileReader.close();
}
}
tnx everybody for their answers.
i think i found the way to pass al the text file by the next simple loop code:
String currentLine = "";
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((tempLine = bufferedReader.readLine())!= null){
if (tempLine.isEmpty() == false ){
currentLine = currentLine+tempLine+"\n";
}
}
in that way i'm copying the text file line by line and send it to the client by 1 string and than i can do whatever i want.
tnx every1.
peace

Java socket server not responding

I am getting started with java sockets just out of inquisitiveness.
I wrote a small piece of code, a server and a client.
The server accepts a string and converts it to upper case and returns to the client.
I want the server to be able to handle multiple clients and have a persistent connection.
Here is the server code :
package server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
public class Server {
private ServerSocket listener;
private ArrayList<Socket> clients;
public Server() throws IOException{
clients = new ArrayList<Socket>();
listener = new ServerSocket(7575);
}
public Server(int port) throws IOException{
clients = new ArrayList<Socket>();
listener = new ServerSocket(port);
}
public void start() throws IOException, InterruptedException{
Thread one = new Thread(){
public void run(){
while (true){
Socket socket = null;
try {
socket = listener.accept();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (socket.isConnected()){
try {
socket.setKeepAlive(true);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
clients.add(socket);
System.out.println(socket.getRemoteSocketAddress().toString());
}
}
}
};
Thread two = new Thread(){
public void run(){
try {
while (true){
work();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
one.start();
two.start();
one.join();
two.join();
stop();
}
private void stop() throws IOException{
listener.close();
}
private void work() throws IOException{
if (clients.size() == 0){
return;
}
for(int i = 0; i < clients.size(); i++){
Socket socket = clients.get(i);
if (!socket.isClosed()){
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String data = br.readLine();
if (data == null) continue;
out.println(data.toUpperCase());
}
else{
clients.remove(socket);
}
}
}
}
package entry;
import java.io.IOException;
import server.Server;
public class Main {
public static void main(String args[]) throws IOException{
Server server = new Server();
try {
server.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and here is the client :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Main {
public static void main(String args[])throws IOException{
Socket socket = new Socket("192.168.0.110", 7575);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedReader sr = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter pr = new PrintWriter(socket.getOutputStream(), true);
while (true){
System.out.println("\n\nEnter a string : ");
String inp = br.readLine();
if (inp.equals("quit")) break;
pr.println(inp);
System.out.println("The response is : " + sr.readLine());
}
socket.close();
}
}
Strange thing here is when I set a breakpoint in the server code and step through the code in eclipse, the code is working exactly as expected i.e I am getting the response in the client.
But when I run it directly in eclipse, I am not getting the response in the client.
Cannot understand what is going wrong.
Edit
I seem to have fixed the issue.
Here is the code snippet :
Thread two = new Thread(){
public void run(){
try {
while (true){
Thread.sleep(1000); //This is the added line
work();
}
} catch (IOException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
But I am still confused about what made the timing difference.
Is there any cleaner way to achieve this ?
I've solved the problem with a different approach.
Here is the new Approach:
ServerHandler.java :
package server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
public class ServerHandler extends Thread{
private Socket socket;
private BufferedReader in;
private PrintWriter out;
private ArrayList<Socket> clients;
public ServerHandler(Socket socket) throws IOException{
this.socket = socket;
clients = new ArrayList<Socket>();
if (!clients.contains(socket)){
clients.add(this.socket);
System.out.println(this.socket.getRemoteSocketAddress());
}
}
#Override
public void run(){
while (true){
if (clients.isEmpty()) break;
String str = null;
for (int i = 0; i < clients.size(); i++){
Socket socket = clients.get(i);
if (socket.isClosed()){
clients.remove(socket);
continue;
}
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
out = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
str = in.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.println(str.toUpperCase());
}
}
}
}
Main.java [for running the server] :
package entry;
import java.io.IOException;
import java.net.ServerSocket;
import server.ServerHandler;
public class Main {
public static void main(String args[]) throws IOException{
ServerSocket listener = new ServerSocket(7575);
try{
while (true){
new ServerHandler(listener.accept()).start();
}
}
catch(Exception e){
e.printStackTrace();
}
finally{
listener.close();
}
}
}
Ok, Here we go.I don't understand the use of Arraylist for maintaining Connections unless You are handling the messy details for each Client.
The most used or prefered approach for handling multiple clients at a time can be understood in terms of an example:
Server.java
import java.net.ServerSocket;
import java.io.IOException;
class Server {
public static void main(String[] args) throws IOException {
try( ServerSocket ss = new ServerSocket(3333)) { // try with resources
new ServerThread(ss.accept()).start();
}
}
}
As you can see, I just defined a Class that will listen for Client connections, and as soon a request is made to the server it will start a Thread which is defined in the next class. A point to be noted here is the use of Try-with-Resources block. Any class that implements the Closeable interface can be enclosed within this try statement. The try-with-resources automatically handles closing of streams or connections for me. This means, you remove all your redundant try-catch blocks from your code and use this try instead.
Now,
ServerThread.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class ServerThread extends Thread {
Socket s = null;
public ServerThread(Socket s) {
super("ServerThread");
this.s = s;
}
public void run() {
try( PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
BufferedReader stream = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader write = new BufferedReader(new InputStreamReader(System.in))) {
System.out.println("In Server");
String in, out;
while ((in = stream.readLine()) != null) {
System.out.println("Msg 4m client: " + in);
if(in.equals("bye"))
break;
out = write.readLine();
pw.println(out);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Observe the try-with-resources statement over here, We can initialize multiple Connections/Input-Output Streams here, All of the opened connection will automatically be closed as soon as the compiler returns from try statement.Also, Observe the while statement, it will keep on running until the client is sending messages, and will quit if the message is "bye".
Finally, a Client program that sends request to the server.
Client.java
import java.net.Socket;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
class Client {
public static void main(String[] args) {
try( Socket s = new Socket("localhost", 3333);
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
BufferedReader stream = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader write = new BufferedReader(new InputStreamReader(System.in)) ) {
System.out.println("In Client");
String in;
while ((in = write.readLine()) != null) {
pw.println(in);
if(in.equals("bye"))
break;
System.out.println("Msg 4m server: " + stream.readLine());
}
} catch(IOException e) {
System.err.println("Exception: " + e);
}
}
}
Notice, the while Statement here, it will loop until the user is entering messages, and if the message is "bye", it will quit.Rest of the program can be easily understood from above explanation.

Multi Client chat Server Java

i am coding a multi client chat server.i have a server folder that contains Server.java and three client folders namely client1,client2,client3 containing java files resp.now when every client joins the server i try to send a text but the server does not picks the message.the problem is in the void run() try method. till the while(true) loop everything works.
Server code:
Chat.java
import java.net.*;
import java.io.*;
import java.util.*;
class Chat implements Runnable {
Socket skt = null;
DataInputStream dis = null;
DataOutputStream dos = null;
PrintWriter pw = null;
TreeMap<Socket, String> tm;
public Chat(Socket skt, TreeMap<Socket, String> tm) {
this.skt = skt;
this.tm = tm;
}
public void run() {
try {
dis = new DataInputStream(skt.getInputStream());
String msg = "";
while (true) {
msg = dis.readUTF();
Set s = tm.keySet();
Iterator itr = s.iterator();
while (itr.hasNext()) {
String k = (String) itr.next();
Socket v = (Socket) tm.get(k);
dos = new DataOutputStream(v.getOutputStream());
dos.writeUTF();
}
}
} catch (Exception e) {
System.out.println(e);
} finally {
try {
dis.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
}
}
Server.java
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.TreeMap;
class Server
{
public static void main(String dt[])
{
ServerSocket sskt=null;
Socket skt=null;
DataInputStream dis=null;
DataOutputStream dos=null;
TreeMap <String,Socket>tm=new TreeMap<String,Socket>();
try
{
sskt=new ServerSocket(1234);
System.out.println("Waiting for Clients");
while(true)
{
skt=sskt.accept();
dis=new DataInputStream(skt.getInputStream());
dos=new DataOutputStream(skt.getOutputStream());
String user=dis.readUTF();
String pass=dis.readUTF();
if(user.equals(pass))
{
dos.writeBoolean(true);
tm.put(user,skt);
Chat ch=new Chat(skt,tm);
Thread t=new Thread(ch);
t.start();
}
else
{
dos.writeBoolean(false);
}
} //end of while.
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
try
{
dos.close();
dis.close();
skt.close();
sskt.close();
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
}
Client Code:
Send.java
import java.io.*;
import java.net.*;
class Send implements Runnable {
Socket skt = null;
public Send(Socket skt) {
this.skt = skt;
System.out.println(skt);
}
public void run() {
InputStreamReader isrout = null;
BufferedReader brout = null;
PrintWriter pw = null;
DataInputStream dis = null;
try {
// Thread.sleep(2000);
System.out.println("Send a text");
isrout = new InputStreamReader(System.in);
brout = new BufferedReader(isrout);
pw = new PrintWriter(skt.getOutputStream(), true);
do {
String msg = brout.readLine();
pw.println(msg);
} while (!msg.equals("bye"));
} catch (Exception e) {
System.out.println(e);
} finally {
try {
pw.close();
brout.close();
isrout.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
}
}
Client1.java
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;
class Client1 {
public static void main(String dt[]) {
Socket skt = null;
InputStreamReader isr = null;
BufferedReader br = null;
DataOutputStream dos = null;
DataInputStream dis = null;
try {
skt = new Socket("127.0.0.1", 1234);
System.out.println("Connected to server");
System.out.println(skt);
isr = new InputStreamReader(System.in);
br = new BufferedReader(isr);
dos = new DataOutputStream(skt.getOutputStream());
dis = new DataInputStream(skt.getInputStream());
System.out.println("Enter a username");
String user = br.readLine();
dos.writeUTF(user);
System.out.println("Enter a password");
String pass = br.readLine();
dos.writeUTF(pass);
if (dis.readBoolean()) {
System.out.println("User Authenticated");
} else {
System.out.println("Incorrect username or password");
}
Send sn = new Send(skt);
Thread t = new Thread(sn);
t.start();
} catch (Exception e) {
System.out.println(e);
} finally {
try {
// skt.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
}
}
After writing any value using an outputstream you need to flush it to actually send it.
In the Chat and Server class where you use DataOutputStream, you need to call this after writing data.
dos.flush();
In the Client class after sending data through the PrintWriter you need to call this.
pw.flush();

Android java : How to send message from server to a specific client any time

I tried to send message from server to client but if i send message the client needs to connect again or println again...
So how does it work?
I tried to println again from server to client but the client wont receive it.
So how to send message to a specific client at any time.
Server:
package server.server.com;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.ArrayList;
public class Server extends Thread {
private static ServerSocket serverSocket;
public static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
static InputStream is;
static OutputStream os;
static byte[] buf;
static BufferedReader reader;
static BufferedWriter writer;
static double ConsoleMessage;
public static String output;
static BufferedReader bufferedReader2;
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(12345);
} catch (IOException e) {
System.out.println("Could not listen on port: 12345");
}
System.out.println("Server started. Listening to the port 12345");
while (true) {
try {
clientSocket = serverSocket.accept();
inputStreamReader = new InputStreamReader(
clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
PrintWriter out = new PrintWriter(
clientSocket.getOutputStream(), true);
InputStream inputStream = new ByteArrayInputStream(
bufferedReader.readLine().getBytes(
Charset.forName("UTF-8")));
bufferedReader2 = new BufferedReader(new InputStreamReader(
inputStream));
output = bufferedReader2.readLine();
System.out.println(output);
out.flush();
out.close();
inputStreamReader.close();
clientSocket.close();
} catch (IOException ex) {
System.out.println("Problem in message reading");
}
}
}
}
Client:
client = new Socket();
client.connect(
new InetSocketAddress(
"IP-ADDRESS",
PORT),
5000);
in = new BufferedReader(
new InputStreamReader(
client.getInputStream()));
printlng = new PrintWriter(
client.getOutputStream());
printlng.println(mLongitude);
printlng.flush();
try {
if ((Response = in
.readLine()) != null) {
....
You should take a look at http://developer.android.com/google/gcm/index.html. Maybe you could take advantage of push notifications in your app.
Maybe you can do something like this
Server:
private boolean sendMessage(final String msg, final String dstIp, final int dstPort) {
DatagramSocket sendSocket = null;
try {
sendSocket = new DatagramSocket();
final InetAddress local = InetAddress.getByName(dstIp);
final int msg_length = msg.length();
final byte[] message1 = msg.getBytes();
final DatagramPacket sendPacket = new DatagramPacket(message1,
msg_length, local, dstPort);
sendSocket.send(sendPacket);
} catch (final Exception e) {
e.printStackTrace();
return false;
} finally {
if (sendSocket != null) {
sendSocket.disconnect();
sendSocket.close();
sendSocket = null;
}
}
return true;
}
Client:
public static void receiveMessage() {
if ((socket == null) || socket.isClosed()) {
socket = new DatagramSocket(BROADCAST_PORT);
socket.setSoTimeout(5000);
}
try {
idMsgs.clear();
while ((socket != null) && !socket.isClosed()) {
socket.setReuseAddress(true);
socket.setSoTimeout(10000);
try {
final byte[] receiveBuffer = new byte[sizepck];
final DatagramPacket packet = new DatagramPacket(
receiveBuffer, receiveBuffer.length);
socket.receive(packet);
} catch (final SocketTimeoutException e) {
} catch (final Throwable e) {
}
}
} catch (final Throwable e1) {
try {
Thread.sleep(TIME_RETRY);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
finally {
if (socket != null) {
socket.close();
}
}
}

My Server and Client socket program just hangs without printing anything

Why does nothing get printed out to the console?
I have a server socket which starts a new thread for each client. It reads a line from the client outputs it and sends a response of its own. This is printed on the client side. Here's the code:
The client code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
PrintWriter out = null;
BufferedReader in = null;
Socket echoSocket=null;
try {
echoSocket = new Socket("localhost", 8999);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
for(int i=0;i<20;i++) {
out.print("Sending to Server"+i);
System.out.println("Received from Server"+in.readLine());
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
try {
in.close();
} finally {
try {
out.close();
} finally {
echoSocket.close();
}
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
The server code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Server {
/**
* #param args
*/
public static void main(String[] args) {
try {
final ServerSocket server = new ServerSocket(8999);
final ExecutorService threadPool = Executors.newFixedThreadPool(2);
while (true) {
try {
final Socket sock = server.accept();
threadPool.submit(new Callable<Void>() {
#Override
public Void call() throws Exception {
BufferedReader br = null;
PrintWriter out = null;
try {
br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
out = new PrintWriter(sock.getOutputStream(), true);
for (int i = 0; i < 20; i++) {
String readLine = br.readLine();
System.out.println(readLine);
out.print(readLine + "response");
}
} finally {
try {
br.close();
} finally {
try {
out.close();
} finally {
sock.close();
}
}
}
return null;
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Well for one, you should probably println instead of print on your writers (in both client and server).

Categories

Resources