Server-client communication by using IP address doesn't work - java

Server application and client application are running in different computers. I want to send some message from client to server. The server should receive it and display. But in my case it's not happening. Nothing happens in server computer when something is sent.
This is my client program:
import java.io.*;
import java.net.*;
public class EchoClient {
//private static final String IP="194.47.46.36";
public EchoClient() {
}
public void establish() {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
//echoSocket = new Socket(InetAddress.getLocalHost(), 8080);
echoSocket = new Socket("195.47.46.76", 4444);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
try {
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
if (userInput.equals("Bye."))
break;
System.out.println("echo: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
} catch (IOException ioe) {
System.out.println("Failed");
System.exit(
-1);
}
}
}

Related

Server doesn't receive message in client-server application

In my client-server application, the client sends message to Server and the Server should display the message. But in my case, the client is only able to send but the server can't achieve it.
I have tried with different port numbers (i.e. 8080, 8000, 4444 etc). It seems that the socket can set up the connection, but I really don't know why the server can't read the input from client.
This is my complete project (I have ignored the main classes for both application here, because I have nothing more than just calling the methods):
EchoServer.java:
package client.server;
import java.io.*;
import java.net.*;
public class EchoServer {
public EchoServer() {
}
public void establish() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8080);
} catch (IOException e) {
System.out.println("Could not listen on port: 1234");
System.exit(-1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.out.println("Accept failed: 1234");
System.exit(-1);
}
PrintWriter out = null;
BufferedReader in = null;
try {
out = new PrintWriter(
clientSocket.getOutputStream(), true);
in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
} catch (IOException ioe) {
System.out.println("Failed in creating streams");
System.exit(-1);
}
String inputLine, outputLine;
try {
while ((inputLine = in.readLine()) != null) {
out.println(inputLine);
if (inputLine.equals("Bye.")) {
break;
}
}
} catch (IOException ioe) {
System.out.println("Failed in reading, writing");
System.exit(-1);
}
try {
clientSocket.close();
serverSocket.close();
} catch (IOException e) {
System.out.println("Could not close");
System.exit(-1);
}
}
}
EchoClient.java:
package server.client;
import java.io.*;
import java.net.*;
public class EchoClient {
public EchoClient() {
}
public void establish() {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
//echoSocket = new Socket(InetAddress.getLocalHost(), 1234);
echoSocket = new Socket(InetAddress.getLocalHost(), 8080);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
try {
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
if (userInput.equals("Bye.")) {
break;
}
System.out.println("echo: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
} catch (IOException ioe) {
System.out.println("Failed");
System.exit(
-1);
}
}
}
Your server doesn't write the incoming text to the console but only back to the client which doesn't handle incoming text from the server yet.
(out isn't System.out but Socket.out!)
In your server you are listening with readLine() in whileloop
while ((inputLine = in.readLine()) != null) {
System.out.println("inputLine "+inputLine);
which is nothing but the inputstream from client. The above SOP will print the message from client. Try to flush your streams because it won't print until your buffer is full.
Code seems to be fine. If you write some thing on PrintWriter at both server & client ends, you will get output.
Add below code in server: ( After creating Socket with accept() API)
out.println("Hello from Server");
Add below code in client ( After creating Socket)
out.println("Hello from client");
Other suggestions:
1) Create a thread once you accept a Socket Connection at server and that thread should handle all IO processing
2) You can create thread at client end too after creating Socket with Server. The new thread should handle all IO processing

Java Sockets: Sending Stdin and GUI data from Client to Server, Server not reading and responding as expected

Apologies as I asked something similar last night, but I have narrowed my problem down. I am wondering how to make my Java TCP Socket Server read in the data sent using the printWriter(out) in the Client code from a GUI as it does from the command line stdin.
I have the following classes as an example and everything works fine until the GUI comes into the equation. The data is being sent over to the Server from the GUI as I can echo it on the server side, but it is not being read and parsed properly as the stdin is. Nothing is being sent back to the client. I have tried flushing, using different streams and adding line separators all over the place to no avail. There is also a Protocol class that handles the data on the Server side.
public class KnockKnockServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
System.out.println("Waiting for client...");
} 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);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine, outputLine;
KnockKnockProtocol kkp = new KnockKnockProtocol();
outputLine = kkp.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("Bye.")) {
break;
}
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
.
public class KnockKnockClient {
public static PrintWriter out = null;
public static String sendAnswer;
public static void Client() {
//JButton Action Listener
saveAnswer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ButtonModel b = group.getSelection();
if (b.getActionCommand() == "A") { sendAnswer = radioA.getText(); }
String data = "รท" + sendAnswer;
out.println(data);
}
});
}
public static void main(String[] args) throws IOException {
KnockKnockClient.Client();
Socket kkSocket = null;
//PrintWriter out = null;
BufferedReader in = null;
try {
kkSocket = new Socket("localhost", 4444);
out = new PrintWriter(kkSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: localhost.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: localhost.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer, fromUser;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("Bye."))
break;
fromUser = stdIn.readLine();
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
out.close();
in.close();
stdIn.close();
kkSocket.close();
}
}

Client-Server application JAVA, server don't receive data

I have a problem when the client send data to the server. When I send data from the server to the client everything is okay. I received this message: "client receive: message" but then when I send "client's message", my server do not receive it.
import java.io.IOException;
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws IOException {
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);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
String inputLine, outputLine;
outputLine = "message";
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
System.out.println("server receive: " + inputLine);
outputLine = "second message";
out.println(outputLine);
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == startButton) {
this.main.getContentPane().remove(homePanel);
String name = this.name.getText();
String result;
try {
connectionToServer();
if ((result = in.readLine()) != null) {
System.out.println("client receive: " + result);
out.println("client's message");
}
} catch(IOException err) {
System.out.println("error");
}
}
}
public void connectionToServer() throws IOException {
try {
this.socket = new Socket("localhost", 4444);
this.in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
this.out = new PrintWriter(this.socket.getOutputStream(), true);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: taranis.");
System.exit(1);
}
}
your actionPerformed method just link the server and do nothing.
The server closed after send a message.
watch: while ((inputLine = in.readLine()) != null)
if client don't send any message,code will break,then you closed the server.

Java Chat System

I'm having problems with broadcasting the messages sent by each client. The server can receive each message from multiple clients but it cannot broadcast it. Error message says connection refused
Client:
public void initializeConnection(){
try {
host = InetAddress.getLocalHost();
try{
// Create file
FileWriter fstream = new FileWriter("src/out.txt", true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(host.getHostAddress()+'\n');
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
clientSocket = new Socket(host.getHostAddress(), port);
outToServer = new PrintWriter(clientSocket.getOutputStream(), true);
inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}
catch(IOException ioEx) {
ioEx.printStackTrace();
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==quit){
try {
outToServer.close();
clientSocket.close();
System.exit(1);
} catch (IOException e1) {
e1.printStackTrace();
}
}
else if(e.getSource()==button){
if(outMsgArea.getText()!=null || !outMsgArea.getText().equals("")){
String message = outMsgArea.getText();
outToServer.println(clientName+": "+message);
outMsgArea.setText("");
}
}
}
public void run(){
try {
while(true){
String message = inFromServer.readLine();
System.out.println(message);
inMsgArea.append(message+'\n');
}
} catch (IOException e) {
e.printStackTrace();
}
}
Server:
import java.io.*;
import java.net.*;
import java.util.*;
public class RelayChatServer {
public static int port = 44442;
ServerSocket server;
public void listenSocket(){
try{
server = new ServerSocket(port);
} catch (IOException e) {
System.out.println("Could not listen on port 4444");
System.exit(-1);
}
while(true){
ClientWorker w;
try{
//server.accept returns a client connection
w = new ClientWorker(server.accept());
Thread t = new Thread(w);
t.start();
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
}
}
protected void finalize(){
//Objects created in run method are finalized when
//program terminates and thread exits
try{
server.close();
} catch (IOException e) {
System.out.println("Could not close socket");
System.exit(-1);
}
}
public static void main(String[] args) {
new RelayChatServer().listenSocket();
}
}
class ClientWorker implements Runnable {
private Socket client;
//Constructor
ClientWorker(Socket client) {
this.client = client;
}
public void run(){
String line;
BufferedReader in = null;
PrintWriter out = null;
try{
in = new BufferedReader(new
InputStreamReader(client.getInputStream()));
//out = new
// PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
System.out.println("in or out failed");
System.exit(-1);
}
while(true){
try{
line = in.readLine();
//Send data back to client
//out.println(line);
//Append data to text area
if(line!=null && line!=""){
System.out.println(line);
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("out.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
Socket s;
PrintWriter prnt;
while ((strLine = br.readLine()) != null && (strLine = br.readLine()) != "") {
// Print the content on the console
s = new Socket(strLine, 44441);
prnt = new PrintWriter(s.getOutputStream(),true);
prnt.println(line);
System.out.println(strLine);
prnt.close();
s.close();
}
//Close the input stream
//inp.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}catch (IOException e) {
System.out.println("Read failed");
e.printStackTrace();
System.exit(-1);
}
}
}
}
The Exception starts:
java.net.ConnectException: Connection refused: connect
The expanded output looks like:
I'm somewhat confused as to why you attempt to open a new socket (do you intend for this to be sent back to the client?) based on a string you read from a file. Perhaps
s = new Socket(strLine, 44441);
prnt = new PrintWriter(s.getOutputStream(),true);
should be:
prnt = new PrintWriter(client.getOutputStream(),true);
As currently I don't see where you are sending anything back to the client.
Edit: ok try something like the following:
static final ArrayList<ClientWorker> connectedClients = new ArrayList<ClientWorker>();
class ClientWorker implements Runnable {
private Socket socket;
private PrintWriter writer;
ClientWorker(Socket socket) {
this.socket = socket;
try {
this.writer = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException ex) { /* do something sensible */ }
}
public void run() {
synchronized(connectedClients) {
connectedClients.add(this);
}
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) { /* do something sensible */ }
while (true) {
try {
String line = in.readLine();
if (line != null && line != "") {
synchronized (connectedClients) {
for (int i = 0; i < connectedClients.size(); ++i){
ClientWorker client = connectedClients.get(i);
client.writer.println(line);
}
}
}
} catch (IOException e) { /* do something sensible */ }
}
}
}

Multithreaded chat-server in Java

I'm trying to implement a server-client socket program in Java that can support multiple clients, but my class that performs the multithreading always crashes whenever my client connects to my server.
import java.io.*;
import java.net.*;
public class ClientWorker extends Thread{
Socket cwsocket=null;
public ClientWorker(Socket cwsocket){
super("ClientWorker");
cwsocket=cwsocket;
}
public void run(){
try {
PrintWriter out = new PrintWriter(cwsocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(cwsocket.getInputStream()));
String serverinput, serveroutput="";
out.println(serveroutput);
while ((serverinput = in.readLine()) != null) {
out.println(serveroutput);
if (serveroutput.equals("Terminate"))
break;
}
out.close();
in.close();
cwsocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Whenever I create a PrintWriter object, a NullPointerException exception is thrown, and I'm not sure why it continues to happen. Below are my server and client classes. What am I doing wrong?
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[]args)throws IOException{
ServerSocket serversocket=null;
final int PORT_NUM=4444;
boolean flag=true;
try{
System.out.println("Listening for connection");
serversocket=new ServerSocket(PORT_NUM);
}catch(IOException e){
System.out.println("Could not listen to port: "+PORT_NUM);
System.exit(-1);
}
while(flag){
new ClientWorker(serversocket.accept()).start();
}
System.out.println("Terminating server...");
serversocket.close();
}
}
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args){
Socket socket=null;
PrintWriter out=null;
BufferedReader in=null;
BufferedReader userInputStream=null;
String IP="127.0.0.1";
try{
socket = new Socket(IP, 4444);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
System.out.println("Unknown host:" + IP);
System.exit(1);
} catch (IOException e) {
System.out.println("Cannot connect to server...");
System.exit(1);
}
String userInput, fromServer;
try{
userInputStream = new BufferedReader(new InputStreamReader(System.in));
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("Terminate"))
break;
userInput = userInputStream.readLine();
if (userInput != null) {
System.out.println("> " + userInput);
out.println(userInput);
}
}
}catch(IOException e){
System.out.println("Bad I/O");
System.exit(1);
}
try{
out.close();
in.close();
userInputStream.close();
socket.close();
System.out.println("Terminating client...");
}catch(IOException e){
System.out.println("Bad I/O");
System.exit(1);
}catch(Exception e){
System.out.println("Bad I/O");
System.exit(1);
}
}
}
In
public ClientWorker(Socket cwsocket){
super("ClientWorker");
cwsocket=cwsocket;
}
You need to do
this.cwsocket=cwsocket;
Or rename the parameter so it doesn't shadow the member of the same name.

Categories

Resources