Hi I struggle with my client/server homeworks in java
I have to connect to a given server and do some "talking", but I have a problem where after I write to the server I get no response from it (timeout in tests before my "never reaches" comment in the code)
public void run(PrintStream sysout, String host, int port, String myname) {
OutputStream out = null;
BufferedReader in = null;
for (int i = 0; i < COUNT; i++) {
try{
this.connect(host,port); // same as clientSocket constructor
out = this.clientSocket.getOutputStream();
in = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
out.write(myname.getBytes());
out.flush();
String income = in.readLine(); // never reaches !!!
sysout.print(income);
sysout.flush();
out.close();
}catch(IOException e){
sysout.println(HelloServer.ERR_MESSAGE);
sysout.flush();
continue;
}
}
Related
I write a FTP application using UDP Datagram Protocol , and I need the client side read from file 100 character and send it in 5 parts , 20 characters in each part , when I run my program I get this error :
Exception in thread "main" java.lang.IllegalArgumentException: illegal length or offset. I want the server get each line in five parts but sort it accordingly.
this is my code :
import java.net.*;
import java.io.*;
public class FTPClient
{
public static void main(String[] args)
{
final int SIZE=100;
DatagramSocket skt= null;
DatagramPacket pkt = null;
BufferedReader read= null;
int port = 3131;
try
{
skt=new DatagramSocket(2121);
read= new BufferedReader(new FileReader("input.txt"));
String line = read.readLine();
byte[] lineByte = new byte[SIZE];
lineByte = line.getBytes();
InetAddress add = InetAddress.getByName("localhost");
for(int i=0;i<100;i+=20)
{
pkt = new DatagramPacket(lineByte,i,20,add,port);
skt.send(pkt);
}
}
catch(IOException e)
{
System.out.println(e.getMessage()); }
finally
{
skt.close();
// read.close();
}
}
}
Your code with comments at problem areas. If you still have problems resolving the issues after reading my comments, just add a comment and I will explain more
public static void main(String[] args) {
final int SIZE = 100;
DatagramSocket skt = null;
DatagramPacket pkt = null;
BufferedReader read = null;
int port = 3131;
try {
skt = new DatagramSocket(2121);
read = new BufferedReader(new FileReader("input.txt"));
String line = read.readLine(); // how long is the line?
byte[] lineByte = new byte[SIZE]; // this is a redundant assignment
lineByte = line.getBytes(); // now the length of the lineBytes is "unknown"
InetAddress add = InetAddress.getByName("localhost");
for (int i = 0; i < 100; i += 20) { // you should check the length of lineBytes instead of 100
pkt = new DatagramPacket(lineByte, i, 20, add, port);
skt.send(pkt);
}
}
catch (IOException e) {
System.out.println(e.getMessage());
}
finally {
skt.close();
// read.close();
}
}
I am working on small Server/ Client application (console base) in Java. The purpose of the application is to send number from client to server and in the server add (+1) with it and return back to client. Client print the line and send back to server the increased number until it reaches 10.
The connectivity between both classes is working properly, but when I put BufferedReader before PrintWriter in server class, then the application doesn't work and also doesn't throws any error.
Client Code:
int count = 1;
PrintWriter out = null;
BufferedReader in = null;
Socket socket = null;
try {
socket = new Socket("localhost",3700);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
while(in.read() != 10){
out.println(count);
out.flush();
System.out.print(in.read());
};
out.close();
in.close();
socket.close();
Server Code:
ServerSocket serverSocket = null;
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
int count = 1;
try {
serverSocket = new ServerSocket(3700);
} catch (IOException e) {
e.printStackTrace();
}
try {
socket = serverSocket.accept();
} catch (IOException e) {
e.printStackTrace();
}
out = new PrintWriter(socket.getOutputStream());
out.println(count);
out.flush();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(in.read() != 10){
count = in.read();
count++;
};
in.close();
out.close();
serverSocket.close();
socket.close();
while(in.read() != 10){
count = in.read();
count++;
};
You are reading characters and throwing them away, and you are ignoring end of stream. It should be:
int ch;
while((ch = in.read()) !- -1 && ch != 10){
count = ch;
count++;
};
and similarly for the server side. The -1 test is the end of stream condition, which happens when the peer closes the connection.
But more probably you should be using readLine() and Integer.parseInt():
String line;
while ((line = in.readLine()) != null)
{
int value = Integer.parseInt(line);
// etc.
}
I have a Java server uploading files for the android client. It does the upload but when it is finished, it keeps throwing:
Error::java.net.SocketException: Socket is closed
I searched the code a lot, but didn't find anything. Since it is throwing after uploading the files, I think problem is at the end of code after last for loop, but I see nothing wrong. Any ideas guys?
class ClientThread extends Thread {
// the socket where to listen/talk
String Type;
Socket socket;
ObjectInputStream sInput;
ObjectOutputStream sOutput;
// my unique id (easier for deconnection)
int id;
// Constructore
ClientThread(Socket socket) throws InterruptedException {
// a unique id
id = ++uniqueId;
this.socket = socket;
/* Creating both Data Stream */
System.out.println("Thread trying to create Object Input/Output Streams");
while (!jobdone) {
try {
// create output first
sOutput = new ObjectOutputStream(socket.getOutputStream());
sInput = new ObjectInputStream(socket.getInputStream());
// read the username
OutputStream os = socket.getOutputStream();
FileInputStream fis = null;
DataOutputStream dos = new DataOutputStream(os);
String Request = (String) sInput.readObject();
System.out.println(Request);
String[] todoname = Request.split("\\#reza-hp");
String name = todoname[0];
System.out.println("Connecting...");
File fil = new File("D://Users//ProfileImages//reza");
System.out.println(fil);
File[] Files = fil.listFiles();
System.out.println(Files);
for (int count = 0; count < Files.length; count++) {
System.out.println(Files[count].getName());
}
os = socket.getOutputStream();
dos = new DataOutputStream(os);
dos.writeInt(Files.length);
for (int count = 0; count < Files.length; count++) {
dos.writeUTF(Files[count].getName());
}
for (int count = 0; count < Files.length; count++) {
int filesize = (int) Files[count].length();
dos.writeInt(filesize);
}
for (int count = 0; count < Files.length; count++) {
int filesize = (int) Files[count].length();
byte[] buffer = new byte[filesize];
fis = new FileInputStream(Files[count].toString());
BufferedInputStream bis = new BufferedInputStream(fis);
// Sending file name and file size to the server
bis.read(buffer, 0, buffer.length); // This line is
// important
dos.write(buffer, 0, buffer.length);
dos.flush();
fis.close();
}
dos.close();
os.close();
} catch (Exception e) {
System.out.println("Error::" + e);
}
}
Thread.sleep(5000);
Server.shutdown();
}
}
You should use ServerSocket to listen for incoming connections from your client application. Plain Socket is preatty straightforward. Open connection, exchange data, close connection, dispose. You could rebind your socket, but this is not the way you should do.
ServerSocket server=new ServerSocket(yourPort);
Socket clientSocket=server.listen(); // here you will block until incoming connection
Check docs for more info here
your socket is getting closed from Otherside
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.
I am trying to stream an array of strings accross a network. I can send a single string but once I try sending an array of strings I run into problems. I did some research and came up fix which works without errors in the IDE, but then the program crashes when I run it externally. I have narrowed it down to an infinite loop that I have accidently created. I will pastebin all the code as there is too much to put up on here.
Here is the summary of what I am trying to achieve...
Open text file
Read in line by line (each line into a separate string inside of an
array)
Once file read is complete, start streaming each individual string
Have a for loop on the recieve end placing the strings back into
another array
And finally, on the server side, break up each part of the string
into 5 different strings
Here is my client class:
public class Transfers {
public int port = 1223;
//public String Ip = LoginForm.IP;
//public String ip = null;
public static Socket login = null;
public static Socket sock = null;
public static PrintWriter outStream = null;
private static BufferedReader inStream = null;
private static boolean ON = false;
public static String authorize = null;
public static boolean connected = true;
public static void transfers(String IP, int port, String content) throws UnknownHostException, IOException {
try {
login = new Socket(IP, port);
//System.out.println("Connected for streaming");
outStream = new PrintWriter(login.getOutputStream(), true);
outStream.println(content);
} catch (UnknownHostException ex) {
Logger.getLogger(Transfers.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Transfers.class.getName()).log(Level.SEVERE, null, ex);
login.close();
}
}
public static String[] recieveArray(String IP) throws UnknownHostException, IOException {
String[] farray = null;
sock = new Socket(IP, 1224);
inStream = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String count = inStream.readLine();
int counter = Integer.parseInt(count);
System.out.println("counter");
for (int i = 0; i < counter; i++) {
inStream = new BufferedReader(new InputStreamReader(sock.getInputStream()));
farray[i] = inStream.readLine();
System.out.println(farray[i]);
}
return farray;
}
}
Here is my server class:
public class Specials {
private static ServerSocket server = null;
private static Socket client = null;
private static PrintWriter outStream = null;
private static BufferedReader inStream = null;
private static boolean ServerOn = true;
public static String message = "";
public static String command = null;
static public InetAddress IP = null;
public static String status = null;
private static String file = "accounts.dat";
private static int counter;
public static void arraysend(String filename) throws FileNotFoundException, IOException {
counter = 0;
FileInputStream fstream = new FileInputStream("AppData/" + filename);
String strLine;
String[] filearray;
try (DataInputStream in = new DataInputStream(fstream)) {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
filearray = new String[1000];
for (int j = 0; j < 10; j++) {
filearray[j] = br.readLine();
counter++;
}
in.close();
}
try {
server = new ServerSocket(1224);
client = server.accept();
IP = client.getInetAddress();
outStream = new PrintWriter(client.getOutputStream(), true);
filearray[0] = Integer.toString(counter);
outStream.println(filearray[0]);
for (int i = 1; i < counter; i++) {
outStream = new PrintWriter(client.getOutputStream(), true);
outStream.println(filearray[i]);
}
client.close();
server.close();
} catch (IOException ex1) {
Logger.getLogger(Specials.class.getName()).log(Level.SEVERE, null, ex1);
}
}
}
I do not get any error messages, The application just crashes. I am including pastebins of my code below for convenience.
Client code
Server code
Any help would be appreciated, thanks.
c
There's so many issues with this code I am not sure where to start. Here is a (non-exhaustive) list:
You are using static modifiers for your class variables and
methods. They do not serve any purpose being defined this way and
and make debugging miserable. Remove them all.
Create only those class variables that are actually required in order
to maintain state. Currently most of the variables you declare at a
class level could actually be declared within the methods that use
them.
In your client side recieveArray method you are reinitializing your
buffered reader during every iteration of the receive loop. This is
most likely leading to missing data since you will be trashing some
data that had been buffered in the previous reader (and no longer
available from the socket input stream).
In your client side recieveArray method, you are reading up to
count strings, but on your server side you send count - 1
strings, because you are storing the count in the first element of
the array you had previously filled.
This code:
for (int j = 0; j < 10; j++) {
filearray[j] = br.readLine();
counter++;
}
for (int i = 1; i < counter; i++) {
outStream = new PrintWriter(client.getOutputStream(), true);
outStream.println(filearray[i]);
}
In the code I posted above (server side) you are also recreating the
output stream to the client in every iteration of the send loop.
Fix all those problems and retest, then come ask followup questions if need be.
see your code in Transfers class you are intialize farray array with null
.and also you are using this in for loop
inStream = new BufferedReader(new InputStreamReader(sock.getInputStream()));
and in Specials class you again use in for
outStream = new PrintWriter(client.getOutputStream(), true);