errors in getting & sending Data (String ,Int ) in socket java - java

hi every one i have a project that get someString and intand from client and i want to send them to my server.but i have problem in getting this . i get nothing or wrong things. please help me.
Client:
//build a socket.
public void connectclient() throws IOException
{
socket = new Socket("localhost", 9097);
System.out.println("connect to server on port 9097");
}
public void startstreams() throws IOException , ClassNotFoundException
{
in = socket.getInputStream();
out = socket.getOutputStream();
dos = new DataOutputStream(out);
dis = new DataInputStream(in);
writer = new OutputStreamWriter(out);
reader = new InputStreamReader(in);
breader = new BufferedReader(reader);
bwriter = new BufferedWriter (writer);
w = new PrintWriter(out, true);
}
public void writeSocketMyJson(String n) throws IOException
{
w = new PrintWriter(out, true);
w.println(n);
w.flush();
w.close();
}
massage1 = "username";
//send username that get from login form to server.
public void sendusername() throws IOException
{
writeSocketMyJson(massage1);
}
massage2 ="admin";
//send password that get from login form to server.
public void sendpassword() throws IOException
{
writeSocketMyJson(massage2);
}
//send access level to server.
public void sendaccess(int l) throws IOException
{
dos.writeInt(l);
dos.flush();
}
sendaccess(21);
Server:
//build server.
public void connectserver() throws IOException
{
listener = new ServerSocket(9097);
System.out.println("Server is running on port 9097 ...");
}
//wait for new connection.
public void waitforclient() throws IOException
{
socket = listener.accept();
System.out.println("A new client connected to the server");
}
public void startstreams() throws IOException
{
in = socket.getInputStream();
out = socket.getOutputStream();
dos = new DataOutputStream(out);
dis = new DataInputStream(in);
writer = new OutputStreamWriter(out);
reader = new InputStreamReader(in);
bwriter = new BufferedWriter (writer);
breader = new BufferedReader (reader);
}
public String readSocket() throws IOException
{
breader = new BufferedReader(reader);
while (true)
{
massage = new String();
massage = breader.readLine();
if (massage.equals(null) == false)
{
break;
}
}
return(massage);
}
//get username that client send it.
public String getusername() throws IOException, ClassNotFoundException
{
try
{
username = new String();
username = readSocket();
System.out.println("the username is : " + username);
}
catch(IOException IOE)
{
IOE.printStackTrace();//if there is an error, print it out
}
return(username);
}
//get password that client send it.
public String getpassword() throws IOException, ClassNotFoundException
{
try
{
password = new String();
password = readSocket();
System.out.println("the password is : " + password);
}
catch(IOException IOE)
{
IOE.printStackTrace();//if there is an error, print it out
}
return(password);
}
//get commend from client.
//admin or user send which commend 21-add new information 22-show information
public int getaccess() throws IOException
{
System.out.println("server get access : " + dis.readInt());
return(dis.readInt());
}
but when i call getpassword()i get nothing .
when i callgetaccess()i get nothing.
why? please help me.
i have main class too that control the orders
main:
//build Server & Client
Server server = new Server();
Client client = new Client();
//Start Server & Client
server.connectserver();
client.connectclient();
//Server wait for new connection
server.waitforclient();
//start the Streams
server.startstreams();
client.startstreams();
client.sendusername();
String msg1 =server.readSocket();
client.sendpassword();
String msg2 =server.readSocket();
client.sendaccess();
int n = getaccess();

Your code is full of nonsense. You do things like
breader = new BufferedReader (reader);
public String readSocket() throws IOException
{
breader = new BufferedReader(reader);
and like
w = new PrintWriter(out, true);
public void writeSocketMyJson(String n) throws IOException
{
w = new PrintWriter(out, true);
and like
password = new String();
password = readSocket();
I would suggest that you just throw it all away and begin from scratch, with some sample code for java sockets, of which there exist numerous on the interwebz.
The thing to remember is that you cannot just pretend that a socket is a regular stream, and you cannot just create a BufferedReader on top of it. At any given moment you need to know exactly how many bytes were sent, and therefore exactly how many bytes to expect to receive.
So generally, on the sending side you cannot write a string and expect on the receiving side the end of the string to be detected with an end-of-line. On the sending side you need to first write the length of the string, as a 32-bit int, so on the receiving side you know you are expecting exactly 4 bytes that contain the length of the string that follows. Then, you can read the exact right number of bytes that make up the string. Of course, do not forget that in java, a character is 2 bytes long.

Related

How to give an automated response back when receiving a specific message from the client (Java, sockets)

I basically was trying to give a response back from my server if my client sends me the message "Hello mr server". However it doesn't.
Here is my code :
public class Server {
public static final int PORT = 6666;
public static void main(String[] args) throws IOException {
new Server().runServer();
}
public void runServer() throws IOException {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Server up and ready for connections.....");
while (true) {
Socket socket = serverSocket.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); //for fetching data
String str = br.readLine(); //for fetching data
System.out.println("Client Data:" + str + '\n');
String dataSendingToClient = "gg";
OutputStreamWriter os = new OutputStreamWriter(socket.getOutputStream()); //for sending data
PrintWriter out = new PrintWriter(os); //for sending data
out.println(dataSendingToClient);
os.flush();
if (br.equals("hey mr server")){
OutputStreamWriter os2 = new OutputStreamWriter(socket.getOutputStream()); //for sending data
PrintWriter out2 = new PrintWriter(os); //for sending data
out2.println("hey mr client");
os.flush();
}
}
}
}
You are using br.equals("hey mr server") which will always return false, since br is not a String, but a BufferedReader
Instead you should use your already defined str variable str.equals("hey mr server")
Also note that with your current code, your server will only read one message from the client before moving on to the next connection
If you want your server to read more messages from a single client, you will need to loop until the client sends a disconnect message/the socket closes
while(true)
{
Socket socket = serverSocket.accept();
BufferedReader br = [...];
PrintWriter out = [...];
for(String message = br.readLine(); message != null; message = br.readLine())
{
//do stuff
//message is each line from the client
}
}
If you have multiple clients trying to connect, you will need to multithread the connections
I would recommend a class to enclose the connection details and use Stacks to poll if the client sent data
public static void main(String[] args) //or whatever other method you're running in
{
List<Connection> clients = new ArrayList<Connection>(); //some data structure to hold the clients
//start accepting connections
new Thread(new Runnable()
{
public void run()
{
while(true)
Connection client = new Connection(serverSocket.accept());
}
}).start();
//do something with the clients, read/write/whatever
}
private class Connection extends Runnable
{
private BufferedReader reader;
private PrintWriter writer;
private Queue<String> messages;
public Connection(Socket s)
{
reader = [...];
writer = [...];
messages = new LinkedList<String>();
}
public void run()
{
//just keep reading
while(true)
messages.add(reader.readLine();
}
public String read()
{
messages.poll();
}
public void write(String msg)
{
writer.write(msg);
writer.flush();
}
}
Note: take that as rough pseudocode

How to assign four threads to four methods from different files? (multithreaded java socket programming)

I am trying to create a text messaging program with three files (main function file, client file, server file) where text messages can be sent and received at the same time, multiple times (ability to send multiple messages by pressing enter after each message, ability to receive multiple messages after connection after the other side presses enter after each message)
There are four threads (one thread for receiving messages on server, one thread for sending messages on server, one thread for receiving messages on client, one thread for sending messages on client)
If "-l" is present on the command line, it will run as a server, otherwise it will run as a client
Command line arguments to run server:
java DirectMessengerCombined -l 3000
Command line arguments to run client:
java DirectMessengerCombined 3000
The command line arguments (String[] args) should be accessible to all 3 files.
Here is the code where the threads are created:
Code of main function file:
import java.io.IOException;
public class DirectMessengerCombined implements Runnable
{
public static void main(String[] args) throws IOException
{
DirectMessengerClient client1 = null;
DirectMessengerServer server1 = null;
Thread ServerRead = new Thread ();
Thread ServerWrite = new Thread ();
Thread ClientRead = new Thread ();
Thread ClientWrite = new Thread ();
for (int i = 0; i < args.length; i++)
{
if (args.length == 1)
{
client1 = new DirectMessengerClient(args);
client1.ClientRun(args);
ClientRead.start();
ClientWrite.start();
}
else if (args.length == 2)
{
server1 = new DirectMessengerServer(args);
server1.ServerRun(args);
ServerRead.start();
ServerWrite.start();
}
i=args.length + 20;
}
}
#Override
public void run()
{
//This method is just to get rid of the "implements" error
//There are four threads, so which one is accessing this method??
}
}
In the following code there are comments such as "//I would like this to be the ServerRead thread method". I would like to know how to make that comment viable or put it into real code somehow to make it work with the corresponding threads in the main function file
Code of Server file:
import java.io.*;
import java.net.*;
import java.util.*;
import javax.imageio.IIOException;
public class DirectMessengerServer implements Runnable
{
private String[] serverArgs;
private static Socket socket;
public boolean keepRunning = true;
int ConnectOnce = 0;
public DirectMessengerServer(String[] args) throws IOException
{
// set the instance variable
this.serverArgs = args;
run();
}
public String[] ServerRun(String[] args) throws IOException
{
serverArgs = args;
serverArgs = Arrays.copyOf(args, args.length);
return serverArgs;
}
//I would like this to be the ServerRead thread method
public void run()
{
try
{
if(ConnectOnce == 0)
{
int port_number1 = Integer.valueOf(serverArgs[1]);
ServerSocket serverSocket = new ServerSocket(port_number1);
socket = serverSocket.accept();
ConnectOnce = 4;
}
while(keepRunning)
{
//Reading the message from the client
//BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromClient = br.readLine();
System.out.println("Message received from client: "+ MessageFromClient);
// ServerSend.start();
runSend();
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
}
}
//I would like this to be the ServerWrite thread method
public void runSend()
{
while(keepRunning)
{
System.out.println("Server sending thread is now running");
try
{
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
//creating message to send from standard input
String newmessage = "";
try
{
// input the message from standard input
BufferedReader input= new BufferedReader(
new InputStreamReader(System.in));
String line = "";
line= input.readLine();
newmessage += line + " ";
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
String sendMessage = newmessage;
bw.write(sendMessage + "\n");
bw.flush();
System.out.println("Message sent to client: "+sendMessage);
ConnectOnce = 4;
// run();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
}
}
}
}
Client file code:
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class DirectMessengerClient
{
private String[] clientArgs;
private static Socket socket;
public boolean keepRunning = true;
public DirectMessengerClient(String[] args) throws IOException
{
// set the instance variable
this.clientArgs = args;
run(args);
}
public String[] ClientRun(String[] args)
{
clientArgs = args;
clientArgs = Arrays.copyOf(args, args.length);
return clientArgs;
}
//I would like this to be the ServerWrite thread method
public void run(String args[]) throws IOException
{
System.out.println("Client send thread is now running");
while(keepRunning)
{
String port_number1= args[0];
System.out.println("Port number is: " + port_number1);
int port = Integer.valueOf(port_number1);
String host = "localhost";
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
//creating message to send from standard input
String newmessage = "";
try
{
// input the message from standard input
BufferedReader input= new BufferedReader(new InputStreamReader(System.in));
String line = "";
line= input.readLine();
newmessage += line + " ";
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
String sendMessage = newmessage;
bw.write(sendMessage + "\n");
bw.flush();
System.out.println("Message sent to server: "+sendMessage);
runClientRead(args);
}
}
//I would like this to be the ClientRead thread method
public void runClientRead(String args[]) throws IOException
{
System.out.println("Client recieve/read thread is now running");
//Integer port= Integer.valueOf(args[0]);
//String host = "localhost";
//InetAddress address = InetAddress.getByName(host);
//socket = new Socket(address, port);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromServer = br.readLine();
System.out.println("Message received from server: " + MessageFromServer);
}
}
My question is how to make those methods work with the threads inside the main function file and/or how to turn the comments into real code for the corresponding threads in the main file?
EDIT: I am able to get it to send one message at a time successfully now, is there a way to make it so I can send and receive multiple messages at a time?

can i use multiple times (input/output)stream for different types of data transfer between two nodes [duplicate]

This question already has answers here:
Java multiple file transfer over socket
(3 answers)
Closed 6 years ago.
In this code I use multiple times of retrieve input-output data from two nodes. ... when I use more than two times input output stream it generated this type of error while running this code I need different input and output and that I want to store but unfortunate if I used more than three-time input/output stream it show error
public class Server {
private static Socket socket;
public void connect() throws IOException{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");
socket = serverSocket.accept();
}
//Server is running always. This is done using this while(true) loop
//Reading the message from the client
public void first() throws IOException{
connect();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String number = br.readLine();
System.out.println("Message received from client is "+number);
//Multiplying the number by 2 and forming the return message
String returnMessage;
try
{
int numberInIntFormat = Integer.parseInt(number);
int returnValue = numberInIntFormat*2;
returnMessage = String.valueOf(returnValue) + "\n";
}
catch(NumberFormatException e)
{
//Input was not a number. Sending proper message back to
client.
returnMessage = "Please send a proper number\n";
}
second();
String e=br.readLine();System.out.println(e);
}
public void second() throws IOException{
//Sending the response back to the client.
String returnMessage="Second";
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Message sent to the client is "+returnMessage);
bw.flush();
}
public static void main(String args[]) throws IOException{
Server obj = new Server();
obj.first();
// obj.second();
}public class Server {
private static Socket socket;
public void connect() throws IOException{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");
socket = serverSocket.accept();
}
//Server is running always. This is done using this while(true) loop
//Reading the message from the client
public void first() throws IOException{
connect();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String number = br.readLine();
System.out.println("Message received from client is "+number);
//Multiplying the number by 2 and forming the return message
String returnMessage;
try
{
int numberInIntFormat = Integer.parseInt(number);
int returnValue = numberInIntFormat*2;
returnMessage = String.valueOf(returnValue) + "\n";
}
catch(NumberFormatException e)
{
//Input was not a number. Sending proper message back to client.
returnMessage = "Please send a proper number\n";
}
second();
String e=br.readLine();System.out.println(e);
}
public void second() throws IOException{
//Sending the response back to the client.
String returnMessage="Second";
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Message sent to the client is "+returnMessage);
bw.flush();
}
public static void main(String args[]) throws IOException{
Server obj = new Server();
obj.first();
// obj.second();
}
public class client {
private static Socket socket;
//public void connect() throws UnknownHostException, IOException{
//}
public void first() throws IOException{
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String number = "2";
String sendMessage = number + "\n";
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+sendMessage);
String sendMessage1="3333";
bw.write(sendMessage1);
bw.flush();
//second();
}
public void second1() throws IOException{
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr;
isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : " +message);
socket.close();
}
public static void main (String argd[]) throws IOException{
client obj1 = new client();
obj1.first();
}
-----------------------------------------
error
Message received from client is 2
Message sent to the client is Second
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:209)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
InputStream and OutputStream are intended to work with a single source and destination. Once you obtain an InputStream that reads from file/socket/whatever source you can use it for multiple consecutive reads. But once you are done reading from that source you need to invoke close() method on your stream.
Not closing your stream is classic reason for a memory leak in Java. In fact for that reason you ALWAYS expected to surround the usage of your source with try catch and always invoke close() method in finally statement. So to insure that it is always invoked. Further more, since close() method itself can cause an Exception, within final statement you need to surround it with its own try-catch. Starting from java 7 there is a new feature called "try with resources" that deals with this particular issue.
Please read about it here

NumberFormatException(Throwable) error when attempting to connect to a socket

I wrote a program which needs to connect to multiple server sockets. Each time it connects to a server, I try to save the server's InetAddress and localPort as an ArrayList in an ArrayList (connectedServers). So connectedServers is an ArrayList of ArrayLists. Before a new connection to a server is made, I try to check whether the same server is already connected with this client by checking through connectedServers.
While debugging in eclipse, the debugger stops at the line marked "ERROR" in the below code. In eclipse a new tab opens with the heading NumberFormatException(Throwable).<init>(String) line: 197 which shows the message Source not found.
If I take the marked line of code outside the if block, the connection gets made successfully. But I need it to work inside the if block. What can be the problem? The code is as follows.
public static ArrayList<ArrayList<Object>> connectedServers = new ArrayList<ArrayList<Object>>();
public static void main (String args[]) throws IOException {
listeningPort = 1111;
String host = takeInput("Host");
int port = takeInputInt("Port");
Socket a = connectToServer(host, port);
if (a != null) {
//....
}
//....
}
public static String takeInput(String inputName) throws IOException {
System.out.print(inputName+": ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
return input;
}
public static int takeInputInt(String inputName) throws IOException {
System.out.print(inputName+": ");
Scanner inputInt = new Scanner(System.in);
int input = inputInt.nextInt();
return input;
}
public static Socket connectToServer(String host, int port) throws IOException {
ArrayList<Object> element = new ArrayList<>();
element.add(host);
element.add(port);
//println(connectedServers);
//println(element);
//println(connectedServers);
if (connectedServers.contains(element) != true) {
//println(host + " " + port);
Socket fellowServer = new Socket(host, port);//<-------ERROR!!
connectedServers.add(element);
element.remove(host);
element.remove(0);
return fellowServer;
}
else{
return null;
}
}
Something could be wrong in here with input
Scanner inputInt = new Scanner(System.in);
int input = inputInt.nextInt();

Connection Reset in Java

I've been trying to fix this error for days now. Really. I just don't get it. The code is simple enough.. Why is it not working?
public class server
{
public static void main(String[] args)
{
String fileName = null;
try
{
ServerSocket ss = new ServerSocket(9999, 3);
Socket dataSocket = ss.accept();
System.out.println("Server: Connection Established");
InputStream is = dataSocket.getInputStream();
//BufferedReader br = new BufferedReader(new InputStreamReader(is));
Scanner sc = new Scanner(dataSocket.getInputStream());
while(sc.hasNextByte())
{
System.out.println("True");
fileName = fileName+sc.next();
}
FileWriter fw = new FileWriter("server"+fileName);
while(dataSocket != null)
{
fw.write(is.read());
}
fw.flush();
dataSocket.close();
ss.close();
/*String[] nameParts;
nameParts = fileName.split(".");
File f = new File(nameParts[0]+"."+nameParts[1]);
FileOutputStream fos = new FileOutputStream(f);
System.out.println(nameParts[0]);*/
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Above is the server code. The client code is below:
public class client
{
public static void main(String[] args)
{
// Read a file
try
{
Socket dataSocket = new Socket();
dataSocket.connect(new InetSocketAddress(InetAddress.getLocalHost(), 9999));
System.out.println("Client: Connection Established");
OutputStream os = dataSocket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
String fileName = "text.txt";
pw.write(fileName);
File f = new File(fileName);
Scanner sc = new Scanner(f);
/*while(sc.hasNextInt())
{
pw.write(sc.nextInt());
}*/
//pw.flush();
//pw.close();
//dataSocket.close();
/*String[] nameParts = new String[2];
nameParts = args[0].split(".");
while(sc.hasNextByte())
{
os.write(sc.nextByte());5
}*/
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
At first, both client and server just kept waiting for each other to speak, like two shy teenagers. After a few changes, this started to happen. I get the Connection Reset error. Please help. Deadlines!
sc.hasNextByte() remains true until the peer has closed the connection. So you will never get out of this loop. You need to send the filename length ahead of the filename, so you know how much of the incoming data is the filename. Then read the filename, open the file, and read and copy the rest of the stream until EOS.
Optionally, you can write your file name with a lien as below:
pw.write(fileName + "\n");
Or user some writer to writeLine(fileName ).
And in server side, use bufferedReader to read line by line:
while ((line = br.readLine()) != null) {
....
}
Then it can finish the loop if the client is closed.

Categories