ServerSocket cannot read input from Client - java

I'm new to socket programming and I'm just trying out a few things. What I'm trying to do is have a Client that reads a text file, saves the lines from that file in an ArrayList and then send the lines to the Server. This is my code. The connection is successfully established, but when the server tries to read from his BufferedReader, it doesn't get anything:
Server:
import java.io.*;
import java.net.*;
public class Server extends Thread{
ServerSocket sock = null;
Socket client_sock = null;
PrintWriter out = null;
BufferedReader in = null;
Server(int port){
try{
sock = new ServerSocket(port);
}catch(IOException e){
System.out.println("Couldn't create server socket");
e.printStackTrace();
}
}
public void run(){
while (true){
try{
client_sock = sock.accept();
System.out.println("Successfully connected to client" + client_sock);
System.out.println(client_sock.getOutputStream());
System.out.println(client_sock.getInputStream());
out = new PrintWriter(client_sock.getOutputStream(),true);
//System.out.println(out);
in = new BufferedReader(new InputStreamReader(client_sock.getInputStream()));
//System.out.println(in);
System.out.println("Trying to read line sent from client:");
String l;
try{
l = in.readLine();
System.out.println(l);
}catch(IOException e){
System.out.println("Couldn't read line from client");
e.printStackTrace();}
}catch(IOException e){
e.printStackTrace();
break;
}
}
}
public static void main(String[] args){
//Thread t = new Server(Integer.parseInt(args[0]));
//t.start();
Server serv = new Server(10239);
System.out.println(serv.sock);
serv.run();
}
}
Client:
import java.net.*;
import java.io.*;
import java.util.*;
public class Client {
Socket sock = null;
OutputStream toServer = null;
PrintWriter out = null;
InputStream fromServer = null;
BufferedInputStream in = null;
Client(int port){
try{
sock = new Socket("localhost",port);
//System.out.println(sock.getPort());
//System.out.println(sock.getOutputStream());
//System.out.println(sock.getInputStream());
//toServer = sock.getOutputStream();
//System.out.println(sock.getOutputStream());
out = new PrintWriter(sock.getOutputStream());
//System.out.println(out);
//fromServer = sock.getInputStream();
in = new BufferedInputStream(sock.getInputStream());
//System.out.print(in);
}catch(UnknownHostException ue){
System.out.println("Host not known");
}
catch(IOException e){
e.printStackTrace();
}
}
public static void main(String[] args){
Client client = new Client(Integer.parseInt(args[0]));
File f = new File("/Users/--------/Desktop/socket_test.txt");
BufferedReader f_in = null;
try{
f_in = new BufferedReader(new FileReader(f));
}catch(IOException e){
System.out.println("Cannot create FileReader for test file");
}
String line;
ArrayList<String> text = new ArrayList<String>();
try{
while ((line = f_in.readLine()) != null){
text.add(line);
}
}catch(IOException e){
e.printStackTrace();
}
//System.out.println("first line of file");
//System.out.println(text.get(0));
for (String l : text){
System.out.println("Sent the following line:");
System.out.println(l);
client.out.println(l);
}
}
}
This is the output I get for the Client:
Sent the following line:
Similar to the previous constructor
Sent the following line:
the InetAddress parameter specifies
Sent the following line:
the local IP address to bind to.
Sent the following line:
The InetAddress is used for servers that
Sent the following line:
may have multiple IP addresses
Sent the following line:
allowing the server to specify which of
Sent the following line:
its IP addresses to accept client requests on
and this for the Server:
ServerSocket[addr=0.0.0.0/0.0.0.0,localport=10239]
Successfully connected to clientSocket[addr=/127.0.0.1,port=58285,localport=10239]
Trying to read line sent from client:
null
I can't find the reason why this doesn't work, can anybody help me please?

Try to flush the stream after each line :
client.out.println(l);
client.out.flush();

Related

Java Threaded Server Client Messaging Application

I'm trying to make a threaded server client messaging application in java. I'm having trouble sending a message that a client sent to every other client connected to the server. I added all connected threads to an array list so when a message is sent I can iterate over the list and send it to all the clients but this doesn't seem to be working. What am I doing wrong here?
When one client is connected it works perfectly the server echos everything the client says. When two clients are connected only the client that sent the message gets the message. If that same client though send another message the server seems to get hung up and no messages get echoed.
Threaded Server Code
import java.io.*;
import java.net.*;
import java.util.*;
public class ThreadedSever
{
private static final int port=5000;
ArrayList<ServerThread> clientList = new ArrayList<ServerThread>();
//Threaded Server
public ThreadedSever(){
System.out.println("A multi-threaded server has started...");
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
}catch(Exception e){
System.out.println("Could not create a server socket: " + e);
}
//Chat with the client until breaks connection or says bye
try{
while(true){
System.out.println("Waiting for client communication");
Socket currentSocket = serverSocket.accept();
//Create a new thread to deal with this connection
clientList.add(new ServerThread(currentSocket));
System.out.println(clientList);
}
}catch(Exception e){
System.out.println("Fatal Server Error!");
}
}
//Inner class to handle individual commincation
private class ServerThread extends Thread{
//Possible add name to then get private messages
private Socket sock;
private DataInputStream in = null;
private DataOutputStream out = null;
public ServerThread(Socket sock){
try{
this.sock = sock;
in = new DataInputStream(this.sock.getInputStream());
out = new DataOutputStream(this.sock.getOutputStream());
System.out.print("New client connection established");
out.writeUTF("Type bye to exit, otherwise, prepare to be echoed");
start();
}catch(Exception e){
System.out.println("Oops");
}
}
public void run(){
try{
String what = new String("");
while(!what.toLowerCase().equals("bye")){
what = in.readUTF();
echoMessage(what);
}
}catch(Exception e){
System.out.println("Connection to current client has been broken");
}
finally{
try{
sock.close();
}catch(Exception e){
System.out.println("Error socket could not be closed");
}
}
}
public void echoMessage(String what){
try{
for (ServerThread Thread: clientList) {
in = Thread.in;
out = Thread.out;
System.out.println("Client told me: " + what);
out.writeUTF(what);
}
}catch(Exception e){
}
}
}
public static void main(){
new ThreadedSever();
}
}
Client Code
import java.io.*;
import java.net.*;
public class simpleClient
{
private static final int port= 5000;
private static String server = "localhost";
private static Socket socket = null;
private static DataInputStream input = null;
private static DataOutputStream output = null;
private static InputStreamReader inReader = null;
private static BufferedReader stdin = null;
public static void main(){
try{
socket = new Socket(server, port);
}catch(UnknownHostException e){
System.err.println("Unknow IP address for server");
System.exit(-1);
}
catch(IOException e){
System.err.println("No server found at specified port");
System.exit(-1);
}
catch(Exception e){
System.err.println("Something happened!");
System.exit(-1);
}
try{
input = new DataInputStream(socket.getInputStream());
output = new DataOutputStream(socket.getOutputStream());
inReader = new InputStreamReader(System.in);
stdin = new BufferedReader(inReader);
String what = new String("");
String response;
while(!what.toLowerCase().equals("bye")){
// Expect something from the server and output it when it arrives
response = input.readUTF();
System.out.println("Server said \"" + response + "\"");
//Read a line from the user and send it to the server
what = stdin.readLine();
output.writeUTF(what);
}
}
catch(IOException e){
System.err.println("Broken connection with server");
System.exit(-1);
}
}
}

Unable to get message from client in client-server program in java

I am writing a client-server program in java using TCP/IP. For the purpose, I wrote the following codes:
serversock.java:
import java.net.*;
import java.io.*;
public class serversock {
public static void main(String[] args) throws IOException
{
ServerSocket sersock = null;
try
{
sersock = new ServerSocket(10007);
}
catch (IOException e)
{
System.out.println("Can't listen to port 10007");
System.exit(1);
}
Socket clientSocket = null;
System.out.println("Waiting for connection....");
try
{
clientSocket = sersock.accept();
}
catch ( IOException ie)
{
System.out.println("Accept failed..");
System.exit(1);
}
System.out.println("Conncetion is established successfully..");
System.out.println("Waiting for input from client...");
PrintWriter output = new PrintWriter(clientSocket.getOutputStream());
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine = input.readLine();
while ( inputLine != null)
{
output.println(inputLine);
System.out.println("Server: " + inputLine);
inputLine = input.readLine();
}
input.close();
clientSocket.close();
sersock.close();
}
}
clientsock.java:
import java.util.*;
import java.io.*;
import java.net.*;
public class clientsock
{
public static void main(String[] args) throws IOException
{
Socket sock = new Socket("localhost",10007);
// Scanner scan = new Scanner(System.in);
PrintWriter output = new PrintWriter(sock.getOutputStream(),true);
BufferedReader input = new BufferedReader( new InputStreamReader(sock.getInputStream()));
String line = null;
BufferedReader stdInput = new BufferedReader( new InputStreamReader(System.in));
System.out.println("Enter data to send to server: ");
line = stdInput.readLine();
while ( (line) != "bye")
{
output.println(line.getBytes());
line = stdInput.readLine();
System.out.println("Server sends: " + input.read());
}
sock.close();
}
}
Now on running the programs I got the following output:
server:
shahjahan#shahjahan-AOD270:~/Documents/java$ java serversock
Waiting for connection....
Conncetion is established successfully..
Waiting for input from client...
Server: [B#4e25154f
shahjahan#shahjahan-AOD270:~/Documents/java$
client:
shahjahan#shahjahan-AOD270:~/Documents/java$ java clientsock
Enter data to send to server:
qwe
sdf
^Cshahjahan#shahjahan-AOD270:~/Documents/java$
The server is recieving different symbols, and client receives nothing. Please help me to solve it.
In the client replace:
output.println(line.getBytes());
with
output.println(line);

Simple Client Server Application, but something is going wrong

I am using Socket and ServerSocket classes to communicate on local host
client sends a no. to server and server computes square of no. and sends back to the client
// Client Class
import java.net.*;
import java.io.*;
class SocketDemo
{
public static void main(String...arga) throws Exception
{
Socket s = null;
PrintWriter pw = null;
BufferedReader br = null;
System.out.println("Enter a number one digit");
int i=(System.in.read()-48); // will read only one character
System.out.println("Input number is "+i);
try
{
s = new Socket("127.0.0.1",10101);
pw = new PrintWriter(s.getOutputStream());
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println("Connection established, streams created");
}
catch(Exception e)
{
System.out.println("Exception in Client "+e);
}
pw.println(i);
System.out.println("Data sent to server");
String str = br.readLine();
System.out.println("The square of "+i+" is "+str);
}
}
// Server Side
import java.io.*;
import java.net.*;
class ServerSocketDemo
{
public static void main(String...args)
{
ServerSocket ss=null;
PrintWriter pw = null;
BufferedReader br = null;
int i=0;
try
{
ss = new ServerSocket(10101);
}
catch(Exception e)
{
System.out.println("Exception in Server while creating connection"+e);
}
System.out.print("Server is ready");
while (true)
{
System.out.println (" Waiting for connection....");
Socket s=null;
try
{
s = ss.accept();
System.out.println("Connection established with client");
pw = new PrintWriter(s.getOutputStream());
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
i = new Integer(br.readLine());
System.out.println("i is "+i);
}
catch(Exception e)
{
System.out.println("Exception in Server "+e);
}
System.out.println("Connection established with "+s);
i*=i;
pw.println(i);
try
{
pw.close();
br.close();
}
catch(Exception e)
{
System.out.println("Exception while closing streams");
}
}
}
}
Please Help
On client side do this after sending data to server
pw.println(i);
pw.flush();

Java UDP server

I am new to Java programming and I am trying to create a UDP server. When I compile the code it says it could not listen to port 4722 and I would like to know why. Below is the code. I would be grateful for any advice.
import java.net.*;
import java.io.*;
public class Server
{
public static void main(String[] args) throws IOException
{
DatagramSocket serverSocket = new DatagramSocket(4722);
Socket clientSocket = null;
byte[] receiveData = new byte[1024];
byte[] sendData = new byte [1024];
boolean command = true;
try
{
serverSocket = new DatagramSocket(4722);
DatagramPacket receivePacket = new DatagramPacket(receiveData,receiveData.length);
System.out.println("Waiting for client...");
}
catch (IOException e)
{
System.err.println("Could not listen on port: 4722.");
System.exit(1);
}
DatagramPacket packet = new DatagramPacket (sendData,sendData.length,4722);
serverSocket.send(packet);
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine, outputLine;
mathematicalProtocol bbm = new mathematicalProtocol();
outputLine = bbm.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null)
{
if(inputLine.equals("Bye."))
break;
outputLine = bbm.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("Bye."))
break;
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
You are initializing serverSocket and then making a new DatagramSocket on the same port again (and you can't do that as it's already bound on the first DatagramSocket). I.e. remove the following line:
serverSocket = new DatagramSocket(4722);
Here is a complete example of client/server UDP communication.
The server read data from a file and send each line to the client.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
/**
* #author nono
*
*/
public class UDPFileSender {
static class Client implements Runnable {
// Reception socket
private DatagramSocket socket;
// UDP packet to receive data into
private DatagramPacket packet;
// Flag for initialisation
private boolean failedInit = true;
/**
* Client constructor.
* #param receptionPort
* #param packetMaxLenght
*/
public Client(int receptionPort, int packetMaxLenght) {
try {
// Create the socket using the reception port
this.socket = new DatagramSocket(receptionPort);
// Init the packet
this.packet = new DatagramPacket(new byte[packetMaxLenght],packetMaxLenght);
this.failedInit = false;
} catch (SocketException e) {
//Port already used or other error
e.printStackTrace();
}
}
#Override
public void run() {
if(failedInit){
return;
}
// Loop undefinitly
while(true){
try {
System.out.println("Waiting for packet...");
// Wait for packet
socket.receive(packet);
// Assuming you are receiving string
String msg = new String(packet.getData());
System.out.println("Received : " + msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
try {
int port = 4722;
//Start a client that can listen
new Thread(new Client(port,1024)).start();
// Creaete a reader
BufferedReader reader = new BufferedReader(new FileReader("File.txt"));
//Create a socket
DatagramSocket socket = new DatagramSocket();
// Create a packet
byte[] data = new byte[1024]; // Max length
DatagramPacket packet = new DatagramPacket(data, data.length);
// Set the destination host and port
packet.setAddress(InetAddress.getByName("localhost"));
packet.setPort(port);
String line = null;
while((line = reader.readLine()) != null){
//Set the data
packet.setData(line.getBytes());
//Send the packet using the socket
System.out.println("Sending : " + line);
socket.send(packet);
Thread.sleep(200);
}
//Close socket and file
reader.close();
socket.close();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
If your file contains :
Hello
World
You should see :
Waiting for packet...
Sending : Hello
Received : HelloWaiting for packet...
Sending : World
Received : World
Waiting for packet...

Android application using Socket to send and receive messages:

I have an android application that I am attempting to use to send and receive messages to a server using socket connection.
I have had all manner of problems sending and receiving. I have been able to do one or the other, at no point both.
I was wondering if someone could help me with a simple exercise that I can compile using BufferedReader and PrintWriter to do so.
I appreciate any help as I am at the point of giving up.
Thanks in advance.... Below are a few shots of what I have tried (Though they are irrelevant to this question, I hope it shows that I have tried before asking here).
private OnClickListener sendClickListener = new OnClickListener(){
public void onClick(View arg0) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}};
public class ClientThread implements Runnable {
public void run() {
try {
EditText dstAddress = (EditText) findViewById(R.id.destinationAddress);
EditText dstMessage = (EditText) findViewById(R.id.messageToTranslate);
EditText dstPort = (EditText) findViewById(R.id.destinationPort);
String address = dstAddress.getText().toString();
String message = dstMessage.getText().toString();
int port = Integer.parseInt(dstPort.getText().toString());
InetAddress serverAddr = InetAddress.getByName(address);
Log.d(".Coursework", "C: Connecting...");
Socket socket = new Socket(serverAddr, port);
connected = true;
while (connected) {
try {
EditText dstTranslation = (EditText) findViewById(R.id.returnedTranslation);
dstTranslation.setText("help me");
Log.d(".Coursework", "C: Sending command.");
PrintWriter out;
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
out.println(language);
out.println(message);
Log.d("ClientActivity", "C: Sent.");
//BufferedReader in;
//in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//String translation = in.readLine();
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
public class ClientConnection {
String address, language, message;
int portNumber;
Socket clientSocket = null;
public ClientConnection(String lan, String mes, String add, int pn) throws IOException{
address = add;
portNumber = pn;
language = lan;
message = mes;
}
public String createAndSend() throws IOException{
// Create and connect the socket
Socket clientSocket = null;
clientSocket = new Socket(address, portNumber);
PrintWriter pw = new PrintWriter(clientSocket.getOutputStream(),true);
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// Send first message - Message is being correctly received
pw.write(language+"\n");
pw.flush();
// Send off the data
// Send the second message - Message is being correctly received
pw.write(message+"\n");
pw.flush();
pw.close();
// Send off the data
// NOTE: Either I am not receiving the message correctly or I am not sending it from the server properly.
String translatedMessage = br.readLine();
System.out.print(translatedMessage);
br.close();
//Log.d("application_name",translatedMessage); Trying to check the contents begin returned from the server.
return "Say What??";
}
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerConnection {
public static void main(String[] args) throws Exception {
// Delete - Using while loop to keep connection open permanently.
boolean status = false;
while( !status){
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
// Delete - Working as of here, connection is established and program runs awaiting connection on 4444
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String language = br.readLine();
String message = br.readLine();
// Test - Works
System.out.println(language);
// Test - Works
System.out.println(message);
// Delete - Working as of here, both messages are passed and applied. Messages are received as sent from client.
TranslateMessage tm = new TranslateMessage();
String translatedMessage = tm.translateMessage(language, message);
// NOTE: This seems to be where I am going wrong, either I am not sending the message correctly or I am not receiving it correctly..
// PrintWriter writer = new PrintWriter(new BufferedOutputStream(clientSocket.getOutputStream()));
PrintWriter pw = new PrintWriter(clientSocket.getOutputStream(),true);
// Send translation back
System.out.println(translatedMessage);
pw.write(translatedMessage+"\n");
pw.write("Return test \n"); // Test message!
pw.flush();
// Send off the data
pw.close();
br.close();
clientSocket.close();
serverSocket.close();
}
}
}
I simply neglected to close the socket connection on the client side. So whilst I doubt what I have done is a model answer to my own question it works of included.

Categories

Resources