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.
Related
I am trying to create a method where a server would run a while loop waiting for enough clients to join. When clients send a string containing "JOIN", the server should create a new thread, update the number of clients connected and run the while loop again. The issue I have is that when I get the client to join, my server updates the number of clients joined, but does not close the loop to check the while statement again and run the loop accordingly.
I am not really sure why it is happening. I have tried to somehow return the run() method of the thread created, but that seems to have no effect on the loop.
public void handleConnection()throws IOException{
while(participants.size() < parts){
System.out.println("Current amount of participants joined: " + participants.size() + " out of " + parts);
s = ss.accept();
System.out.println("New client connection attempt from port " + s.getPort());
CoordinatorThread thread = new CoordinatorThread(s);
//System.out.println("Thread created");
synchronized (participantThreads){
participantThreads.put(thread, s.getPort());
}
//System.out.println("Starting thread");
thread.start();
}
System.out.println("All participants joined:");
int no = 1;
for(int i : participants){
System.out.println(no + ") " + i);
no++;
}
}
public class CoordinatorThread extends Thread{
private PrintWriter pr;
private InputStreamReader in;
private BufferedReader bf;
private Socket socket;
private int pport;
//private boolean joined = false;
public CoordinatorThread(Socket s) throws IOException {
socket = s;
in = new InputStreamReader(socket.getInputStream());
bf = new BufferedReader(in);
pr = new PrintWriter(socket.getOutputStream());
}
public void run(){
String str = null;
try {
str = bf.readLine();
System.out.println("Str: " + str);
} catch (IOException e) {
e.printStackTrace();
}
if(str != null && str.contains("JOIN")){
System.out.println("Not null and contains JOIN");
String[] splitStr = str.split(" ");
pport = Integer.parseInt(splitStr[1]);
participants.add(pport);
pr.println(pport + " join accepted");
pr.flush();
System.out.println("COORD: A new participant has joined - " + pport + " / " + socket.getPort()+"\n" +
"total participants: " + participants.size());
}
}
}
The participant class is simply client class with a socket that connects to the coordinator and sends "JOIN " to join the server.
I'm Playing with a simple Client and Server application using socket, and i attempt to print a message in the console and get a response from the server but nothing shows up, i'm fairly new to sockets so i assume i have a logical error. It's a simple app that i want the client to prompt a user a user for a command (in my case an input string where the server will perform an action based on the 'thcharacter), send it to the server and just display the server response.I'm pretty sure my client isn't correct, can someone points out why i can't write anything from the client console.
package socketProgramming;
import java.io.*;
import java.net.*;
public class MyClient {
#SuppressWarnings("resource")
public static void main(String[] args) {
// TODO Auto-generated method stub
Socket socket= new Socket();
BufferedReader in = null;
String msg;
int port = 2222;
try {
System.out.println("CLient wants to connect on port: "+port);
socket = new Socket(InetAddress.getLocalHost().getHostAddress(), port);
System.out.println("The client is connected");
} catch (UnknownHostException e) {
System.exit(1);
} catch (IOException e) {
System.out.println("connect failed");
System.exit(1);
}
try{
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream output = new PrintStream(socket.getOutputStream());
String text = null;
output.print(text);
while ((text = input.readLine()) != null){
System.out.println("Client "+text);
}
socket.close();
System.out.println("Client Exiting");
}
catch(IOException e) {
System.out.println(e);
}}
}
package socketProgramming;
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String msg = "";
ServerSocket sSocket = null;
Socket clientSocket;
int port = 2222;//Integer.parseInt(args[0]);
try{
sSocket = new ServerSocket(port);
} catch(IOException e){
System.out.println(e);
}
while(true){
try {// listen for a connection from client and accept it.
System.out.println("Server is listenning on host: "
+InetAddress.getLocalHost().getHostAddress() +""
+ " and on port: "
+ port);
clientSocket = sSocket.accept();
System.out.println("Connection accepted");
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// PrintWriter out =
// new PrintWriter(clientSocket.getOutputStream(), true);
PrintStream output = new PrintStream(clientSocket.getOutputStream());
msg = input.readLine();
if(msg != null){
if(msg.charAt(12)=='4'){
System.out.println("reading message "+msg+" ");
output.print("Bye");
sSocket.close();
System.out.println("Server exits");
}else{
if(msg.charAt(12)=='0'){
System.out.println("reading message "+msg+" ");
output.print("OK");
}else if (msg.charAt(12)=='1'){
System.out.println("reading message "+msg+" ");
//Should return IP address
output.print(clientSocket.getInetAddress());
}else if (msg.charAt(12)=='2'){
System.out.println("reading message "+msg+" ");
for(int i = 1; i<=10; ++i){
output.print(i);
output.print(" ");
}
}else if (msg.charAt(12)=='3'){
System.out.println("reading message "+msg+" ");
output.print("GOT IT");
}else{
System.out.println("*******************");
}
}
}
sSocket.close();
System.out.println("Server exits");
}
catch(IOException e) {
System.out.println("accept failed");
System.exit(1);
}
System.out.println("Hello world");
}
}
}
I took some liberties with your code and changed it a bit. It is by no means a perfect version of what you've supplied; however, it should get you pointed in the right direction. These were the problems that were solved:
MyClient was never prompting for user input.
MyServer was sending strings without newlines. MyClient was expecting strings with newlines.
In MyServer, the main socket was being closed at the bottom of the loop. I believe you intended to close the client socket so that the server would loop around and process another client.
In MyServer, you're checking the 13th character of the user's input (because you were indexing the 12th byte (zero based) of the string. I put in brute-force protection against checking the 13th byte of strings that are too short.
Again, I simply corrected certain problems in your code. I may have altered it beyond what your true goals actually are. These examples are intended to get you going on your way...
MyClient.java:
import java.io.*;
import java.net.*;
public class MyClient {
#SuppressWarnings("resource")
public static void main(String[] args) {
// TODO Auto-generated method stub
Socket socket = new Socket();
int port = 2222;
try {
System.out.println("CLient wants to connect on port: " + port);
socket = new Socket(InetAddress.getLocalHost().getHostAddress(), port);
System.out.println("The client is connected");
} catch (UnknownHostException e) {
System.exit(1);
} catch (IOException e) {
System.out.println("connect failed");
System.exit(1);
}
try {
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream output = new PrintStream(socket.getOutputStream());
// Get a line of input from the user.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String inputFromUser = br.readLine();
// Send that line of input to MyServer.
output.println(inputFromUser);
// Print out the response from MyServer.
System.out.println("SERVER RESPONSE: " + input.readLine());
socket.close();
System.out.println("Client Exiting");
} catch (IOException e) {
System.out.println(e);
}
}
}
MyServer.java:
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String msg = "";
ServerSocket sSocket = null;
Socket clientSocket;
int port = 2222;// Integer.parseInt(args[0]);
try {
sSocket = new ServerSocket(port);
} catch (IOException e) {
System.out.println(e);
}
while (true) {
try {// listen for a connection from client and accept it.
System.out.println("Server is listenning on host: " + InetAddress.getLocalHost().getHostAddress() + "" + " and on port: "
+ port);
clientSocket = sSocket.accept();
System.out.println("Connection accepted");
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// PrintWriter out =
// new PrintWriter(clientSocket.getOutputStream(), true);
PrintStream output = new PrintStream(clientSocket.getOutputStream());
msg = input.readLine();
if (msg != null) {
if (msg.length() > 12 && msg.charAt(12) == '4') {
System.out.println("reading message " + msg + " ");
output.println("Bye");
System.out.println("Server exits");
} else {
if (msg.length() > 12 && msg.charAt(12) == '0') {
System.out.println("reading message " + msg + " ");
output.println("OK");
} else if (msg.length() > 12 && msg.charAt(12) == '1') {
System.out.println("reading message " + msg + " ");
// Should return IP address
output.println(clientSocket.getInetAddress());
} else if (msg.length() > 12 && msg.charAt(12) == '2') {
System.out.println("reading message " + msg + " ");
for (int i = 1; i <= 10; ++i) {
output.println(i + " ");
}
} else if (msg.length() > 12 && msg.charAt(12) == '3') {
System.out.println("reading message " + msg + " ");
output.println("GOT IT");
} else {
System.out.println("*******************");
// Invalid question from client, I guess.
output.println("HUH?");
}
}
// Make sure output is flushed to client. It will be, but
// just in case...
output.flush();
}
// We're done with this client. Close his socket.
clientSocket.shutdownOutput();
clientSocket.close();
System.out.println("Closed client socket");
}
catch (IOException e) {
System.out.println("accept failed");
e.printStackTrace();
System.exit(1);
}
System.out.println("Hello world");
}
}
}
The problem is that nobody is actually sending any lines. This is what your client does:
output.print(text); //sends null
while ((text = input.readLine()) != null){ //waits to receive a line
This last part is where your client stops because it waits for input that the server never sends. So here is where the server stops:
msg = input.readLine(); //waits to recieve a line
It never reads in null because you didn't send a line (e.g. ending with '\n'). You can easily fix this problem by replacing your output.print() calls with output.println() calls, so that your readers know the line has end and can be read in now.
This question already has answers here:
Java detect lost connection [duplicate]
(9 answers)
Java socket API: How to tell if a connection has been closed?
(9 answers)
Closed 9 years ago.
I have a java program with Socket. I need to check if client has disconnected. I need a example how to do that. I have researched but I don't understand. So can someone make example code and explane everything.
sorry for bad English
my code:
package proov_server;
//SERVER 2
import java.io.*;
import java.net.*;
class server2 {
InetAddress[] kasutaja_aadress = new InetAddress[1000];
String newLine = System.getProperty("line.separator");
int kliendiNr = 0;
int kilene_kokku;
server2(int port) {
try {
ServerSocket severi_pistik = new ServerSocket(port);
System.out.println("Server töötab ja kuulab porti " + port + ".");
while (true) {
Socket pistik = severi_pistik.accept();
kliendiNr++;
kasutaja_aadress[kliendiNr] = pistik.getInetAddress();
System.out.println(newLine+"Klient " + kliendiNr + " masinast "
+ kasutaja_aadress[kliendiNr].getHostName() + " (IP:"
+ kasutaja_aadress[kliendiNr].getHostAddress() + ")");
// uue kliendi lõime loomine
KliendiLoim klient = new KliendiLoim(pistik,kliendiNr);
// kliendi lõime käivitamine
klient.start();
}
}
catch (Exception e) {
System.out.println("Serveri erind: " + e);
}
}
DataOutputStream[] väljund = new DataOutputStream[1000];
DataInputStream[] sisend = new DataInputStream[1000];
int klient = 0;
int nr;
// sisemine klass ühendusega tegelemiseks
class KliendiLoim extends Thread {
// kliendi pistik
Socket pistik;
// kliendi number
KliendiLoim(Socket pistik2,int kliendiNr) {
nr = kliendiNr;
this.pistik = pistik2;
}
public boolean kontroll(){
try{
System.out.println("con "+pistik.isConnected());
System.out.println("close "+pistik.isClosed());
if(pistik.isConnected() && !pistik.isClosed()){
//System.out.print(con_klient);
return true;
}
}catch(NullPointerException a){
System.out.println("Sihukest klienti pole!!!");
}
kliendiNr --;
return false;
}
public void run() {
try {
sisend[nr] = new DataInputStream(pistik.getInputStream()); //sisend
väljund[nr] = new DataOutputStream(pistik.getOutputStream()); //väljund
}catch (Exception ea) {
System.out.println(" Tekkis erind: " + ea);
}
while(true){
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Sisesta k2sk: ");
String k2sk = null;
k2sk = br.readLine();
/*
String command;
if(k2sk.indexOf(" ") < 0){
command = k2sk;
}else{
command = k2sk.substring(0, k2sk.indexOf(" "));
}
*/
String[] words = k2sk.split("\\s+");
for (int i = 0; i < words.length; i++) {
words[i] = words[i].replaceAll(" ", "");
}
switch(words[0]){
case "suhtle":
if(väljund.length > klient && väljund[klient] != null)
{
väljund[klient].writeUTF("1");
}else{
väljund[klient] = null;
sisend[klient] = null;
System.out.println("Sihukest klienti pole");
}
break;
case "vaheta":
try{
int klinetnr = Integer.parseInt(words[1]);
//if(kontroll(klinetnr) ){
klient = Integer.parseInt(words[1]);
//}
}
catch(NumberFormatException e){
System.out.println("See pole number!!! ");
}
break;
case "kliendid":
if(kliendiNr != 0){
for(int i=1;i <= kliendiNr;i++){
if(kontroll()){
System.out.println("Klient:"+i+" ip: " + kasutaja_aadress[i] );
}else{
System.out.println("Pisi");
väljund[klient] = null;
sisend[klient] = null;
}
}
System.out.println(newLine);
}else{
System.out.println("Kiente pole");
}
break;
}
System.out.println(kliendiNr);
}catch(SocketException a){
System.out.println("Klient kadus");
}
catch(Exception e){
System.out.println(" Viga: " + e);
}
}
}
}
public static void main(String[] args) {
new server2(4321);
}
}
If the client has disconnected properly:
read() will return -1
readLine() returns null
readXXX() for any other X throws EOFException.
The only really reliable way to detect a lost TCP connection is to write to it. Eventually this will throw an IOException: connection reset, but it takes at least two writes due to buffering.
A related thread on Stackoverflow here along with the solution. Basically, the solution says that the best way to detect a client-server disconnect is to attempt to read from the socket. If the read is successfully, then the connection is active.If an exception is thrown during the read there is no connection between the client and the server. Alternatively it may happen that the socket is configured with a timeout value for the read operation to complete. In case, this timeout is exceeded a socket timeout exception will be thrown which can be considered as either the client is disconnected or the network is down.
The post also talks about using the isReachable method - refer InetAddress documentation. However, this method only tells us whether a remote host is reachable or not. This may just one of the reasons for the client to disconnect from the server. You wont be able to detect disconnection due to client crash or termination using this technique.
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)
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.