Below is the code for a client and server which handles multi user chat. But when one client writes "quit" my others current connected client also terminates and I can't then connect another client. Can anybody help with this?
Here is my client code:
class TCPClientsc {
public static void main(String argv[]) throws Exception {
String modifiedSentence;
InetAddress inetAddress = InetAddress.getLocalHost();
System.out.println(inetAddress);
Socket clientSocket = new Socket(inetAddress, 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
CThread write = new CThread(inFromServer, outToServer, 0, clientSocket);
CThread read = new CThread(inFromServer, outToServer, 1, clientSocket);
}
}
class CThread extends Thread {
BufferedReader inFromServer;
DataOutputStream outToServer;
Socket clientSocket = null;
int RW_Flag;
public CThread(BufferedReader in, DataOutputStream out, int rwFlag, Socket clSocket) {
inFromServer = in;
outToServer = out;
RW_Flag = rwFlag;
clientSocket = clSocket;
start();
}
public void run() {
String sentence;
try {
while (true) {
if (RW_Flag == 0) {// write
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
sentence = inFromUser.readLine();
// System.out.println("Writing ");
outToServer.writeBytes(sentence + '\n');
if (sentence.equals("quit"))
break;
} else if (RW_Flag == 1) {
sentence = inFromServer.readLine();
if (sentence.endsWith("quit"))
break;
System.out.println("(received)" + sentence);
}
}
} catch (Exception e) {
} finally {
try {
inFromServer.close();
outToServer.close();
clientSocket.close();
} catch (IOException ex) {
Logger.getLogger(CThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Server code:
class TCPServersc {
static int i = 0;
static SThread tt[] = new SThread[100];
static SThread anot[] = new SThread[100];
public static void main(String argv[]) throws Exception {
String client;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
while (true) {
Socket connectionSocket = welcomeSocket.accept();
i++;
System.out.println("connection :" + i);
BufferedReader inFromClient = new BufferedReader(newInputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
BufferedReader inFromMe = new BufferedReader(new InputStreamReader(System.in));
tt[i] = new SThread(inFromClient, outToClient, tt, 0, connectionSocket, i);
anot[i] = new SThread(inFromMe, outToClient, tt, 1, connectionSocket, i);
}
}
}
// ===========================================================
class SThread extends Thread {
BufferedReader inFromClient;
DataOutputStream outToClient;
String clientSentence;
SThread t[];
String client;
int status;
Socket connectionSocket;
int number;
public SThread(BufferedReader in, DataOutputStream out, SThread[] t, int status, Socket cn, int number) {
inFromClient = in;
outToClient = out;
this.t = t;
this.status = status;
connectionSocket = cn;
this.number = number;
start();
}
public void run() {
try {
if (status == 0) {
clientSentence = inFromClient.readLine();
StringTokenizer sentence = new StringTokenizer(clientSentence, " ");
// ///////////////////////////////////////////////////////////
if (sentence.nextToken().equals("login")) {
String user = sentence.nextToken();
String pass = sentence.nextToken();
FileReader fr = new FileReader("file.txt");
BufferedReader br = new BufferedReader(fr);
int flag = 0;
while ((client = br.readLine()) != null) {
if ((user.equals(client.substring(0, 5))) && (pass.equals(client.substring(6, 10)))) {
flag = 1;
System.out.println(user + " has logged on");
for (int j = 1; j <= 20; j++) {
if (t[j] != null)
t[j].outToClient.writeBytes(user + " has logged on" + '\n');// '\n' is necessary
}
break;
}
}
if (flag == 1) {
while (true) {
clientSentence = inFromClient.readLine();
System.out.println(user + " : " + clientSentence);
for (int j = 1; j <= 20; j++) {
if (t[j] != null)
// '\n' is necessary
t[j].outToClient.writeBytes(user + " : " + clientSentence + '\n');
}
// if(clientSentence.equals("quit"))break;
}
}
}
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (status == 1) {
while (true) {
clientSentence = inFromClient.readLine();
if (clientSentence.equals("quit"))
break;
System.out.println("Server: " + clientSentence);
for (int j = 1; j <= 20; j++) {
if (t[j] != null)
t[j].outToClient.writeBytes("Server :" + clientSentence + '\n');// '\n' is necessary
}
}
}
} catch (Exception e) {
} finally {
try {
// System.out.println(this.t);
inFromClient.close();
outToClient.close();
connectionSocket.close();
} catch (IOException ex) {
Logger.getLogger(SThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
This code has a number of problems.
First off, in the future, please post smaller, concise code fragments that are well formatted. I just had to basically reformat everything in your post.
I see a couple of places where you are catching but doing nothing with exceptions. This is tremendously bad practice. At the least you should be printing/logging the exceptions you catch. I suspect this is contributing to your problems.
I find the RW_Flag very confusing. You should have two client threads then. One to write from System.in to the server and one to read. Don't have one client thread which does 2 things. Same with status flag in the server. That should be 2 different threads.
Instead of int flag = 0; in the server, that should be boolean loggedIn;. Make use of booleans in Java instead of C-style flags and use better variable names. The code readability will pay for itself. Same for status, RW_flag, etc..
Instead of huge code blocks, you should move contiguous code out to methods: handleSystemIn(), handleClient(), talkToServer(). Once you make more methods in the your code, and shrink down the individual code blocks, it makes it much more readable/debuggable/understandable.
You need to have a synchronized (tt) block around each usage of that array. Once you have multiple threads that are all using tt if the main accept thread adds to it, the updates need to be synchronized.
I don't immediately see the problem although the spagetti code is just too hard to parse. I suspect you are throwing and exception somewhere which is the reason why clients can't connect after the first one quits. Other than that, I would continue to use liberal use of System.out.println debugging to see what messages are being sent where.
Related
I am writing tcp client-server program. When the client types "Hello" the server returns a list of files and directories of his current directory. When the client types "FileDownload " it downloads the selected file from the server.
When I type "Hello" it works fine, but when I type "FileDownload ", on the server side it runs twice the else if(received.contains("FileDownload")) block. Because of this the server is sending twice the data which is causing other issues on the client side.
Here is the server code:
public static void main(String[] args) throws IOException {
ServerSocket servSock = new ServerSocket(1333);
String received="";
String[] s = null;
File[] f1;
int i=0;
File f=new File(System.getProperty("user.dir"));
f1=f.listFiles();
for(File f2:f1) {
if(f2.isDirectory())
System.out.println(f2.getName() + "\t<DIR>\t" + i);
if(f2.isFile())
System.out.println(f2.getName() + "\t<FILE>\t" + i);
i++;
}
while (true) {
Socket client = servSock.accept();
InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
PrintWriter pw = new PrintWriter(out, true);
s=f.list();
while(true) {
received = reader.readLine();
if(received.equals("END")) break;
if(received.equals("Hello")) {
System.out.println("Hello-Start");
int length=f1.length;
pw.println(length);
i=0;
for(File f2:f1) {
if(f2.isDirectory())
pw.println(f2.getName() + "\t<DIR>\t" + i);
if(f2.isFile())
pw.println(f2.getName() + "\t<FILE>\t" + i);
i++;
}
pw.println("Options: " + "\tFileDownload <FID>" + "\tFileUpload <name>" + "\tChangeFolder <name>");
System.out.println("Hello-End");
}
else if(received.contains("FileDownload")) {
System.out.println("FileDownload-Start");
int j=-1;
try {
j=Integer.parseInt(received.substring(13).trim());
}catch(NumberFormatException e) {
System.err.println("error: " + e);
}
if(j>0 && j<s.length) {
FileInputStream fi=new FileInputStream(s[j]);
byte[] b=new byte[1024];
System.out.println("file: "+s[j]);
pw.println(s[j]);
fi.read(b,0,b.length);
out.write(b,0,b.length);
System.out.println("FileDownload-End");
}
}
Here is the client code:
public static void main(String[] args) throws IOException {
if ((args.length != 2))
throw new IllegalArgumentException("Parameter(s): <Server> <Port>");
Socket socket = new Socket(args[0], Integer.parseInt(args[1]));
Scanner sc = new Scanner(System.in);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
PrintWriter pw = new PrintWriter(out, true);
while(true) {
String msg="", received="";
String length;
msg = sc.nextLine();
pw.println(msg);
if(msg.equals("END")) break;
if(poraka.equals("Hello")) {
System.out.println();
length = reader.readLine();
for(int i=0;i<Integer.parseInt(length);i++) {
received = reader.readLine();
System.out.println(received);
}
System.out.println("\n"+reader.readLine());
}
else if(msg.contains("FileDownload")) {
System.out.println("FileDownload-Start");
pw.println(msg);
byte[] b=new byte[1024];
File file=new File(reader.readLine().trim());
System.out.println(file.getName().trim());
FileOutputStream fo=new FileOutputStream("D:\\Eclipse WorkSpace\\proekt\\src\\client\\"+file.getName().trim());
System.out.println("file: "+file.getName().trim());
in.read(b,0,b.length);
fo.write(b,0,b.length);
System.out.println("FileDownload-End");
}
I could not find what's causing this issue, so any help possible would be very highly appreciated!
It is because your client requests the data twice:
msg = sc.nextLine();
pw.println(msg); // <-- this is the first time
and then later
else if(msg.contains("FileDownload")) {
System.out.println("FileDownload-Start");
pw.println(msg); // <-- this is the second time
I am coding client-server multithread calculator using java, socket programming.
There's any syntax error, but msgs cannot be received from server.
I think
receiveString = inFromServer.readLine()
does not works. This code is in Client program, in the while(true) loop.
What is the problem?
Here is my full code.
SERVER
import java.io.*;
import java.net.*;
public class Server implements Runnable
{
static int max = 5; //maximum thread's number
static int i = 0, count = 0; //i for for-loop, count for count number of threads
public static void main(String args[]) throws IOException
{
ServerSocket serverSocket = new ServerSocket(6789); //open new socket
File file = new File("src/serverinfo.dat"); //make data file to save server info.
System.out.println("Maximum 5 users can be supported.\nWaiting...");
for(i=0; i <= max; i++) { new Connection(serverSocket); } //make sockets - loop for max(=5) times
try //server information file writing
{
String dataString = "Max thread = 5\nServer IP = 127.0.0.1\nServer socket = 6789\n";
#SuppressWarnings("resource")
FileWriter dataFile = new FileWriter(file);
dataFile.write(dataString);
}
catch(FileNotFoundException e) { e.printStackTrace(); }
catch(IOException e) { e.printStackTrace(); }
}
static class Connection extends Thread
{
private ServerSocket serverSocket;
public Connection(ServerSocket serverSock)
{
this.serverSocket = serverSock;
start();
}
public void run()
{
Socket acceptSocket = null;
BufferedReader inFromClient = null;
DataOutputStream msgToClient = null;
String receiveString = null;
String result = "", sys_msg = "";
try
{
while(true)
{
acceptSocket = serverSocket.accept(); // 접속수락 소켓
count++;
inFromClient = new BufferedReader(new InputStreamReader(acceptSocket.getInputStream()));
msgToClient = new DataOutputStream(acceptSocket.getOutputStream());
System.out.println(count + "th client connected: " + acceptSocket.getInetAddress().getHostName() + " " + count + "/" + max);
System.out.println("Waiting response...");
while(true)
{
if (count >= max+1) // if 6th client tries to access
{
System.out.println("Server is too busy. " + max + " clients are already connected. Client access denied.");
sys_msg = "DENIED";
msgToClient.writeBytes(sys_msg);
acceptSocket.close();
count--;
break;
}
try{ msgToClient.writeBytes(result); }
catch(Exception e) {}
try{ receiveString = inFromClient.readLine(); }
catch(Exception e) // if receiveString = null
{
System.out.println("Connection Close");
count--;
break;
}
System.out.println("Input from client : " + receiveString);
try
{
if(receiveString.indexOf("+") != -1) { result = cal("+", receiveString); }
else if(receiveString.indexOf("-") != -1) { result = cal("-", receiveString); }
else if(receiveString.indexOf("/") != -1) { result = cal("/", receiveString); }
else if(receiveString.indexOf("*") != -1) { result = cal("*", receiveString); }
else if(receiveString.indexOf("+") == -1 || receiveString.indexOf("-") == -1 || receiveString.indexOf("*") == -1 || receiveString.indexOf("/") == -1) { result = "No INPUT or Invalid operation"; }
}
catch(Exception e){ result = "Wrong INPUT"; }
try{ msgToClient.writeBytes(result); }
catch(Exception e) {}
}
}
}
catch(IOException e) { e.printStackTrace(); }
}
}
private static String cal(String op, String recv) //function for calculating
{
double digit1, digit2; //first number, second number
String result = null;
digit1 = Integer.parseInt(recv.substring(0, recv.indexOf(op)).trim());
digit2 = Integer.parseInt(recv.substring(recv.indexOf(op)+1, recv.length()).trim());
if(op.equals("+")) { result = digit1 + " + " + digit2 + " = " + (digit1 + digit2); }
else if(op.equals("-")) { result = digit1 + " - " + digit2 + " = " + (digit1 - digit2); }
else if(op.equals("*")) { result = digit1 + " * " + digit2 + " = " + (digit1 * digit2); }
else if(op.equals("/"))
{
if(digit2 == 0){ result = "ERROR OCCURRED: Cannot be divided by ZERO"; }
else{ result = digit1 + " / " + digit2 + " = " + (digit1 / digit2); }
}
return result;
}
#Override
public void run() {
// TODO Auto-generated method stub
}
}
-----------------------------------------------------------------
CLIENT
import java.io.*;
import java.net.*;
public class Client {
public static void main(String args[]) throws IOException
{
Socket clientSocket = null;
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
BufferedReader inFromServer = null;
DataOutputStream msgToServer = null;
String sendString = "", receiveString = "";
try
{
clientSocket = new Socket("127.0.0.1", 6789); //make new clientSocket
inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
msgToServer = new DataOutputStream(clientSocket.getOutputStream());
System.out.println("Input exit to terminate");
System.out.println("Connection Success... Waiting for permission");
while(true)
{
receiveString = inFromServer.readLine();
if(receiveString.equals("DENIED"))
{
System.out.println("Server is full. Try again later.");
break;
}
else { System.out.println("Connection permitted."); }
System.out.print("Input an expression to calculate(ex. 3+1): ");
sendString = userInput.readLine();
if(sendString.equalsIgnoreCase("exit")) //when user input is "exit" -> terminate
{
clientSocket.close();
System.out.println("Program terminated.");
break;
}
try { msgToServer.writeBytes(sendString); }
catch(Exception e) {}
try { receiveString = userInput.readLine(); }
catch(Exception e) {}
System.out.println("Result: " + receiveString); //print result
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
You've set up your server socket stack wrong.
Your code will make 5 threads, each calling accept on a serversocket.
The idea is to have a single ServerSocket (and not 5, as in your example). Then, this single serversocket (running in a single thread that handles incoming sockets flowing out of this serversocket) will call .accept which will block (freeze the thread) until a connection is made, and will then return a Socket object. You'd then spin off a thread to handle the socket object, and go right back to the accept call. If you want to 'pool' (which is not a bad idea), then disassociate the notion of 'handles connections' from 'extends Thread'. For example, implement Runnable instead. Then pre-create the entire pool (for example, 10 threads), have some code that lets you 'grab a thread' from the pool and 'return a thread' to the pool, and now the serversocket thread will, upon accept returning a socket object, grab a thread from the pool (which will block, thus also blocking any incoming clients, if every thread in the pool is already taken out and busy handling a connection), until a thread returns to the pool. Alternatively, the serversocket code checks if the pool is completely drained and if so, will put on a final thread the job of responding to that client 'no can do, we are full right now'.
I'm not sure if you actually want that; just.. make 1 thread per incoming socket is a lot simpler. I wouldn't dive into pool concepts until you really need them, and if you do, I'd look for libraries that help manage them. I think further advice on that goes beyond the scope of this question, so I'll leave the first paragraph as an outlay of how ServerSocket code ought to work, for context.
I have socket application that i use for communication with a device.
When i open socket i can read status outputs from the machine.
Machine sends some data which is separated by comma ',' and i need to parse only numbers.
The problem is when i parse the data i recieve numbers but i also recieve "empty" strings.
Here is my code:
void startListenForTCP(String ipaddress) {
Thread TCPListenerThread;
TCPListenerThread = new Thread(new Runnable() {
#Override
public void run() {
Boolean run = true;
String serverMessage = null;
InetAddress serverAddr = null;
BufferedWriter out = null;
int redni = 0;
try {
Socket clientSocket = new Socket(ipaddress, 7420);
try {
mc.pushNumbers("Connection initiated... waiting for outputs!"
+ "\n");
char[] buffer = new char[2];
int charsRead = 0;
out =
new BufferedWriter(new OutputStreamWriter(
clientSocket.getOutputStream()));
BufferedReader in =
new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
while ((charsRead = in.read(buffer)) != -1) {
String message = new String(buffer).substring(0, charsRead);
if (message.equals("I,")) {
mc.pushNumbers("\n");
} else {
String m = message;
m = m.replaceAll("[^\\d.]", "");
String stabilo = m;
int length = stabilo.length();
String result = "";
for (int i = 0; i < length; i++) {
Character character = stabilo.charAt(i);
if (Character.isDigit(character)) {
result += character;
}
}
System.out.println("Result:" + m);
}
}
} catch (UnknownHostException e) {
mc.pushNumbers("Unknown host..." + "\n");
} catch (IOException e) {
mc.pushNumbers("IO Error..." + "\n");
} finally {
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
mc.pushNumbers("Connection refused by machine..." + "\n");
}
}
});
TCPListenerThread.start();
}
And the System.out.println(); returns this:
Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:26Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:13
Result:Result:Result:Result:Result:Result:Result:Result:Result:
I just don't know why I can't parse only numbers, there is probably something that machine sends and it isn't parsed by m = m.replaceAll("[^\\d.]", "");
You're building your String incorrectly. It should be:
String message = new String(buffer, 0, bytesRead);
where 'bytesRead' is the count returned by the read() method. It's a byte count, not a char count.
I want to find my Server in my network, when I don't know the ip.
So that's the code I have, but it takes really (!) long to test all IPs:
for (int j = 1; j < 255; j++) {
for (int i = 1; i < 255; i++) {
String iIPv4 = "192.168." + j + ".";
try {
Socket socket = new Socket();
SocketAddress address = new InetSocketAddress(iIPv4 + i, 2652 );
socket.connect(address, 5);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String fromServer;
while ((fromServer = in.readLine()) != null) {
if (fromServer.equals("Connected to CC3000")) {
System.out.println("CC3000 found! : " + iIPv4 + i);
return iIPv4 + i;
}
}
} catch (UnknownHostException e) {
} catch (IOException e) {
}
}
}
so, whats a better way to find the server?
regards
I think that multithreading could help you here, since you don't want to be waiting for each connection to either establish or fail.
You can try say hundreds of sockets at once instead. Also checking that IP is reachable might save you some time.
Code below is really a naive and horrible example since there's no thread management at all, but you get the picture I hope. You should get the result much faster.
public static void findLanSocket(final int port, final int timeout) {
List<Thread> pool = new ArrayList<>();
for (int j = 1; j < 255; j++) {
for (int i = 1; i < 255; i++) {
final String iIPv4 = "192.168." + j + "." + i;
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
System.out.println("TESTING: " + iIPv4);
try {
// First check if IP is reachable at all.
InetAddress ip = InetAddress.getByName(iIPv4);
if (!ip.isReachable(timeout)) {
return;
}
// Address is reachable -> try connecting to socket.
Socket socket = new Socket();
SocketAddress address = new InetSocketAddress(ip, port);
socket.connect(address, timeout);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String fromServer;
while ((fromServer = in.readLine()) != null) {
if (fromServer.equals("Connected to CC3000")) {
System.out.println("CC3000 found! : " + iIPv4);
}
}
} catch (UnknownHostException e) {
} catch (IOException e) {
}
}
});
pool.add(thread);
thread.start();
}
}
// Wait for threads to die.
for (Thread thread : pool) {
try {
if (thread.isAlive()) {
thread.join();
}
} catch (InterruptedException ex) {
}
}
}
Hi i have a problem with my server, everytime i call "dload" the file gets downloaded but i can't use the other commands i have because they get returned as null. Anyone who can see the problem in the code?
Server :
public class TCPServer {
public static void main(String[] args) {
ServerSocket server = null;
Socket client;
// Default port number we are going to use
int portnumber = 1234;
if (args.length >= 1) {
portnumber = Integer.parseInt(args[0]);
}
// Create Server side socket
try {
server = new ServerSocket(portnumber);
} catch (IOException ie) {
System.out.println("Cannot open socket." + ie);
System.exit(1);
}
System.out.println("ServerSocket is created " + server);
// Wait for the data from the client and reply
boolean isConnected = true;
try {
// Listens for a connection to be made to
// this socket and accepts it. The method blocks until
// a connection is made
System.out.println("Waiting for connect request...");
client = server.accept();
System.out.println("Connect request is accepted...");
String clientHost = client.getInetAddress().getHostAddress();
int clientPort = client.getPort();
System.out.println("Client host = " + clientHost
+ " Client port = " + clientPort);
// Read data from the client
while (isConnected == true) {
InputStream clientIn = client.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
clientIn));
String msgFromClient = br.readLine();
System.out.println("Message received from client = "
+ msgFromClient);
// Send response to the client
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("sum")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
Double[] list;
list = new Double[5];
String value;
int i;
try {
for (i = 0; i < 5; i++) {
pw.println("Input number in arrayslot: " + i);
value = br.readLine();
double DoubleValue = Double.parseDouble(value);
list[i] = DoubleValue;
}
if (i == 5) {
Double sum = 0.0;
for (int k = 0; k < 5; k++) {
sum = sum + list[k];
}
pw.println("Sum of array is " + sum);
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("max")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
Double[] list;
list = new Double[5];
String value;
int i;
try {
for (i = 0; i < 5; i++) {
pw.println("Input number in arrayslot: " + i);
value = br.readLine();
double DoubleValue = Double.parseDouble(value);
list[i] = DoubleValue;
}
if (i == 5) {
Arrays.sort(list);
pw.println("Max integer in array is " + list[4]);
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("time")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
Calendar calendar = GregorianCalendar.getInstance();
String ansMsg = "Time is:, "
+ calendar.get(Calendar.HOUR_OF_DAY) + ":"
+ calendar.get(Calendar.MINUTE);
pw.println(ansMsg);
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("date")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
Calendar calendar = GregorianCalendar.getInstance();
String ansMsg = "Date is: " + calendar.get(Calendar.DATE)
+ "/" + calendar.get(Calendar.MONTH) + "/"
+ calendar.get(Calendar.YEAR);
;
pw.println(ansMsg);
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("c2f")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
String celciusValue;
boolean ifRead = false;
try {
pw.println("Input celcius value");
celciusValue = br.readLine();
ifRead = true;
if (ifRead == true) {
double celcius = Double.parseDouble(celciusValue);
celcius = celcius * 9 / 5 + 32;
pw.println(celcius);
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("dload")) {
OutputStream outToClient = client.getOutputStream();
if (outToClient != null) {
File myFile = new File("C:\\ftp\\pic.png");
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0,
mybytearray.length);
outToClient.flush();
outToClient.close();
bis.close();
fis.close();
} catch (IOException ex) {
// Do exception handling
}
System.out.println("test");
}
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("quit")) {
client.close();
break;
}
// if (msgFromClient != null
// && !msgFromClient.equalsIgnoreCase("bye")) {
// OutputStream clientOut = client.getOutputStream();
// PrintWriter pw = new PrintWriter(clientOut, true);
// String ansMsg = "Hello, " + msgFromClient;
// pw.println(ansMsg);
// }
// Close sockets
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("bye")) {
server.close();
client.close();
break;
}
msgFromClient = null;
}
} catch (IOException ie) {
}
}
}
Client:
import java.io.*;
import java.net.*;
public class TCPClient {
public static void main(String args[]) {
boolean isConnected = true;
Socket client = null;
int portnumber = 1234; // Default port number we are going to use
if (args.length >= 1) {
portnumber = Integer.parseInt(args[0]);
}
try {
String msg = "";
// Create a client socket
client = new Socket("127.0.0.1", 1234);
System.out.println("Client socket is created " + client);
// Create an output stream of the client socket
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
// Create an input stream of the client socket
InputStream clientIn = client.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
clientIn));
// Create BufferedReader for a standard input
BufferedReader stdIn = new BufferedReader(new InputStreamReader(
System.in));
while (isConnected == true) {
System.out
.println("Commands: \n1. TIME\n2. DATE\n3. C2F\n4. MAX\n5. SUM\n6. DLOAD\n7. QUIT");
// Read data from standard input device and write it
// to the output stream of the client socket.
msg = stdIn.readLine().trim();
pw.println(msg);
// Read data from the input stream of the client socket.
if (msg.equalsIgnoreCase("dload")) {
byte[] aByte = new byte[1];
int bytesRead;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (clientIn != null) {
try {
FileOutputStream fos = new FileOutputStream("C:\\ftp\\pic.png");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = clientIn.read(aByte, 0, aByte.length);
do {
baos.write(aByte, 0, bytesRead);
bytesRead = clientIn.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
System.out.println("File is successfully downloaded to your selected directory"+ "\n" +"*-----------------*"+ "\n" );
} catch (IOException ex) {
System.out.println("Couldn't dowload the selected file, ERROR CODE "+ex);
}
}
}else{
System.out.println("Message returned from the server = "
+ br.readLine());
}
if (msg.equalsIgnoreCase("bye")) {
pw.close();
br.close();
break;
}
}
} catch (Exception e) {
}
}
}
debugged your code and have two hints:
1)
don't surpress your exceptions. handle them! first step would to print your stacktrace and this question on SO wouldn't ever be opened ;-) debug your code!
2)
outToClient.flush();
outToClient.close(); //is closing the socket implicitly
bis.close();
fis.close();
so in your second call the socket on server-side will already be closed.
first thing:
if (args.length >= 1) {
portnumber = Integer.parseInt(args[0]);
}
This can throw a NumberFormatException, and because args[0] is passed by the user you should handle this.
reading the code also this gave me a problem:
double DoubleValue = Double.parseDouble(value); // LINE 104
Throwing a NumberFormatException when I give c2f as command to the server. You definitively need to handle this exception anywhere in your code and give proper answer to the client, something like:
try{
double DoubleValue = Double.parseDouble(value);
}catch(NumberFormatException e){
// TELL THE CLIENT "ops, the number you inserted is not a valid double numer
}
(in short example, starting from this you have to enlarge the code)
while (isConnected == true) {
I cannot see it! why not use this?
while (isConnected) {
if (msgFromClient != null && msgFromClient.equalsIgnoreCase("sum")){
can be:
if("sum".equalsIgnoreCase(msgFromClient)){
in this case you have no problem with the NullPointerException. (if msgFromClient is null the statement is false).
By the way, date and time command are working fine for me. Check the others.
To fix dload i think you have to delete the line:
outToClient.close();
(EDIT: sorry to maxhax for the same answr, didn't see your answer while writing this)