TCP Server Not Receiving Message From TCP Client (Java) - sockets

It seems like the server is not receiving the message sent from the client as it should. From my understanding the client is writing to the socket outputstream. And the server is reading from the socket inputstream. Please help.
Server Code:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
static final int DEFAULT_PORTNUMBER = 1236;
public static void main(String[] args){
int portnumber;
if(args.length >= 1){
portnumber = Integer.parseInt(args[0]);
}else{
portnumber = DEFAULT_PORTNUMBER;
}
//Setting a server socket and a possible client socket
ServerSocket server = null;
Socket client;
try{
server = new ServerSocket(portnumber);
} catch (IOException e){
e.printStackTrace();
}
while(true){
try{
System.out.println("Waiting for client...");
client = server.accept();
System.out.println("Client accepted... ");
//Read data form the client
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
while(!br.ready()){
System.out.println("No message from client");
}
String msgFromClient = br.readLine();
//System.out.println("Message received from client = " + msgFromClient);
//Send Response
if(msgFromClient != null && !msgFromClient.equalsIgnoreCase("bye")){
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
String ansMsg = "Hello, " + msgFromClient;
pw.println(ansMsg);
}
if(msgFromClient != null && msgFromClient.equalsIgnoreCase("Bye")){
server.close();
client.close();
break;
}
} catch(IOException e) {
e.printStackTrace();
}
//New thread for client
/*new ServerThread(client).start();
System.out.println("Client connection accepted... ");*/
}
}
}
Client Code:
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class TCPClient {
static final int DEFAULT_PORTNUMBER = 1236;
public static void main(String args[]){
Socket client = null;
int portnumber;
//Default port number if not specified as an argument
if(args.length >= 1){
portnumber = Integer.parseInt(args[0]);
}else{
portnumber = DEFAULT_PORTNUMBER;
}
try {
String msg = "";
//Creating a client socket
client = new Socket(InetAddress.getLocalHost(), portnumber);
System.out.println("Client socket is created: " + client);
//Creating an output stream for the client socket
OutputStream clientOUt = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOUt, true);
//Creating an input stream for the client socket
InputStream clientIn = client.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(clientIn));
//Creating a buffered reader for standard input System.in
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter your name. Type Bye to exit.");
//Read data from standard input and write to output stream
msg = stdIn.readLine().trim();
pw.print(msg);
while(!br.ready()){
//System.out.println("No Input From Server");
}
//Read data from input stream of client socket
System.out.println("Message returned from the server = " + br.readLine());
pw.close();
br.close();
client.close();
//Stop operation
if (msg.equalsIgnoreCase("Bye")) {
System.exit(0);
} else {
}
} catch (IOException e) {
System.out.println("I/O error " + e);
}
}
}
Note: I did disable firewall but that did not help.

Found the answer PrintWriter or any other output stream in Java do not know "\r\n". It describes how printwriter doesn't flush properly with printwriter.print() but rather only works when you use printwriter.println().

Related

How to send packet to client with private ip?

I make client and server in c# and i want to send packets between this 2 applications. When client send message to server everything is good, server accept it. But when server try to reply, client not receive message. I think, it is problem because i have private ip (i am not sure, but i think it is NAT - 1 ip and a lot of computers) and my server is running on my VPS.
So, how to reply to client from server?
Client Code:
void SendDataToServer(string Message)
{
IPAddress Ip = Dns.GetHostEntry("mydomain.com").AddressList[0];
int Port = 1234;
IPEndPoint Server = new IPEndPoint(Ip, Port);
byte[] MessageInBytes = Encoding.UTF8.GetBytes(Message);
MySocket.SendTo(MessageInBytes, Server);
}
void ReceiveDataFromServer(int Port) // this is running in background
{
UdpClient Client = new UdpClient(Port);
IPEndPoint Server = new IPEndPoint(IPAddress.Any, Port);
try
{
while (true)
{
byte[] MessageInBytes = Client.Receive(ref Server);
string Message = Encoding.UTF8.GetString(MessageInBytes, 0, MessageInBytes.Length);
MessageBox.Show(Message);
}
}
catch (Exception e)
{
MessageBox.Show(e);
}
}
Server Code:
static void StartReceiveing(int Port) // this is running in background
{
UdpClient Server = new UdpClient(Port);
IPEndPoint Client = new IPEndPoint(IPAddress.Any, Port);
try
{
while (true)
{
byte[] MessageInBytes = Server.Receive(ref Client);
string Message = Encoding.UTF8.GetString(MessageInBytes, 0, MessageInBytes.Length);
Console.WriteLine("Received message: " + Message);
Task.Run(() => ReplyToClient("some text", Client));
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
static void ReplyToClient(string Message, IPEndPoint Client)
{
try
{
byte[] MessageInBytes = Encoding.UTF8.GetBytes(Message);
NetClient.SendTo(MessageInBytes, Client);
Console.WriteLine("Sending reply: " + Message);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}

How to terminate a java program that listens for client's requests to create a socket?

How do I make this program exit when I run it in terminal using the Java JDK in Ubuntu?
I want to type in "end" when this program is running, but I can't get it to work.
It listens for clients and calls a thread thingy to create a socket for the new client.
I can't figure out how to make this program end. I tried everything.
I started learning java yesterday.
Please help me....
import java.net.*; //jave lib
import java.io.*; //io lib
public class MultiServerConnections { //initiate class
public static void main(String[] args) throws IOException {
int portNum = 5342; //set server port number
boolean listen = true;
System.out.println("Listening for Connections"); //print message
ServerSocket server_Socket = null; //set server_Socket to null
try {
server_Socket = new ServerSocket(portNum); //set server port
} catch (IOException e) {
System.err.println("Port " + portNum + " is unavailable"); //port is taken error
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); //set reader
String input;
//while (TCPglobals.checkRequests){
while (listen == true){
new MultiServer(server_Socket.accept()).start();
input = stdIn.readLine();
//if(TCPglobals.checkRequests == false) //|| (input = stdIn.readLine()) == "end")
if(input == "end") {
System.out.println("end connection?");
System.exit(1);
}
}//while
server_Socket.close(); //close server socket
}
}

How can I test, whether my deployed background server application on AWS beanstalk gets messages through a socketstream with an android mobile client?

The overall topic is actually like a Chat Application sending a simple string message to an aws server, which uses the message to make calculations server-side and sending a simple string message as a solution back to the client.
Server: I have written a Server Class and deployed it through eclipse to aws beanstalk. (see code Server)
Client: My android device creates a socket, establishes a successful connection to my aws beanstalk ip and 8080 port, while iterating through an endless while loop in a thread listening to incoming messages from the server. (see code Client and ClientThread)
Problem: My problem is that I don't know how to check whether the server receives the connection request and messages from the client. How do I make sure, that code on aws beanstalk actually runs in background continuously listening for incoming connections? I have deployed the code, does aws beanstalk automatically start the main method of the Server Class and runs it infinitely?
Here's the server code:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String args[]) {
ServerSocket server = null;
System.out.println("Trying to open serversocket!");
try {
server = new ServerSocket(8080);
} catch (IOException e) {
System.out.println("Error on port: 8080 " + ", " + e);
System.exit(1);
}
System.out
.println("Server setup and waiting for client connection ...");
Socket client = null;
try {
client = server.accept();
} catch (IOException e) {
System.out.println("Did not accept connection: " + e);
System.exit(1);
}
System.out
.println("Client connection accepted. Moving to local port ...");
try {
DataInputStream streamIn = new DataInputStream(
new BufferedInputStream(client.getInputStream()));
DataOutputStream streamOut = new DataOutputStream(
new BufferedOutputStream(client.getOutputStream()));
boolean done = false;
String line;
int i = 4;
while (!done) {
line = streamIn.readUTF();
if (line.equalsIgnoreCase(".bye"))
done = true;
else
System.out.println("Client says: " + line);
if (i == 4) {
streamOut
.writeUTF("Actually connected to Server with round "
+ i);
streamOut.flush();
i++;
}
}
streamIn.close();
streamOut.close();
client.close();
server.close();
} catch (IOException e) {
System.out.println("IO Error in streams " + e);
}
}
}
Here's the client code:
package com.amazon.aws.singlesensor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.util.Log;
class Client implements Runnable {
private Socket socket = null;
private InputStream streamIn = null;
private OutputStream streamOut = null;
public InputStream getStreamIn() {
return streamIn;
}
public Client(String serverName, int serverPort) {
System.out.println("Establishing connection. Please wait ...");
try {
socket = new Socket(serverName, serverPort);
Log.d("DEBUG", "Connected: " + socket);
start();
} catch (UnknownHostException uhe) {
Log.d("DEBUG", "Host unknown: " + uhe.getMessage());
} catch (IOException ioe) {
Log.d("DEBUG", "Unexpected exception: " + ioe.getMessage());
}
}
public void start() throws IOException {
streamIn = socket.getInputStream();
streamOut = socket.getOutputStream();
}
public void run() {
try {
streamOut.write(streamIn.read());
streamOut.flush();
} catch (IOException ioe) {
System.out.println("Sending error: " + ioe.getMessage());
stop();
}
}
public void handle(String msg) {
if (msg.equals(".bye")) {
System.out.println("Good bye. Press RETURN to exit ...");
stop();
} else
System.out.println(msg);
}
public void stop() {
try {
if (streamIn != null)
streamIn.close();
if (streamOut != null)
streamOut.close();
if (socket != null)
socket.close();
} catch (IOException ioe) {
System.out.println("Error closing ...");
}
}
public void send(String msg) {
PrintWriter printwriter = new PrintWriter(streamOut);
printwriter.write(msg);
printwriter.flush();
}
}
Here's the ClientThread Code
package com.amazon.aws.singlesensor;
import java.io.IOException;
import java.io.InputStream;
import android.os.Handler;
public class ClientThread extends Thread {
private Client client;
private InputStream input;
private String output;
private Handler handler;
private Runnable runner;
public ClientThread() {
}
public ClientThread(Client client, Handler handler, Runnable runner) {
this.setClient(client);
this.input = client.getStreamIn();
this.handler = handler;
this.runner = runner;
this.output = "";
}
public void run() {
int status = 0;
while (status != -1) {
try {
status = input.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (status != '~'){
try {
status = input.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
output = output + String.valueOf((char) status);
handler.post(runner);
}
output = output + "\n";
}
}
public String giveString(){
return output;
}
public void setClient(Client client) {
this.client = client;
}
public Client getClient() {
return client;
}
}
Thank you for your time!

Socket closed after a while

I have my socket closed or reset by peer after a while,I think garbage collection problem through its reader or writer.
Asynctask for handling responses:
#Override
protected Void doInBackground(Void... params) {
//Log.e("NEW LISTENER THREAD NAME", name);
//initializations
try{
clientSocket = new Socket();
//clientSocket.setTcpNoDelay(true);
clientSocket.connect(new InetSocketAddress(serverURL, dataServerPort));
requestSender = new PrintWriter(new PrintStream(clientSocket.getOutputStream(), true,"UTF-8"));
Sender.Init();
}catch(Exception e){
e.printStackTrace();
}
gsonObj = new GsonBuilder().create();//This the object that handels every comming response
finish = false;
try{
listener = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}catch (IOException e) {
Log.e("FROM CREATING LISTENER", "FROM CREATING LISTENER ========> ");
e.printStackTrace();
}
LOGGED_IN = StaticArea.getLoggedIn(cnt);
if(LOGGED_IN){
USER = StaticArea.getUserName(cnt);
Sender.ResumeUser();
/*********DELEGATING CONNECTING TO SERVER TO BE USED IN SERVICE*************/
Message connectionMsg = new Message();
connectionMsg.obj = Boolean.valueOf(true);
serviceHandler.handleMessage(connectionMsg);
/*********END DELEGATING CONNECTING TO SERVER*************/
}else{
/*********DELEGATING CONNECTING TO SERVER TO BE USED IN SERVICE*************/
Message connectionMsg = new Message();
connectionMsg.obj = Boolean.valueOf(false);
serviceHandler.handleMessage(connectionMsg);
/*********END DELEGATING CONNECTING TO SERVER*************/
}
GoOnline();
while(!finish){
try{
answerS = listener.readLine();
if(answerS != null )//to avoid any null response
if(answerS.contains(Response.MYRESPONSE){
if(MyService.theHandler != null){
Message msg = new Message();
msg.obj = answerS;
MyService.theHandler.sendMessage(msg);
The Sender class is class that has a static methods and uses my sockets output:
public class Sender {
private static Gson gsonObj;
public static void Init() {
gsonObj = new GsonBuilder().create();
}
public static void SendTestRequest(){
try{
Request req = new Request();
req.setR_TYPE(Request.TEST);
String reqString = gsonObj.toJson(req);
requestSender.println(reqString);
requestSender.flush();
}catch(Exception e){
}
}//end method

Java socket programming problem

Hey,
I am trying to run this socket programming code.
This is the code on the server side -
package sockettest;
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket(139);
}
catch (IOException e)
{
System.err.println("not able to listen on port");
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); // Out is Outputstream is used to write to the Client .
BufferedReader in = new BufferedReader( new InputStreamReader(clientSocket.getInputStream())); // in is used to read the Client's input.
String inputLine, outputLine;
out.println("Hey! . Who are you?"); // Writes to client as "Hey! . Who are you?"
while ((inputLine = in.readLine()) != null)
{
// Reads the input from the Client. if it is "bye" the program ends.
if (inputLine.equalsIgnoreCase("Bye"))
{
out.println("Bye");
break;
}
else
{
out.println("Hello Mr. " + inputLine);
}
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
This is the code running on the client side -
import java.io.*;
import java.net.*;
public class Client
{
public static void main(String[] args) throws IOException {
Socket kkSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try
{
kkSocket = new Socket("192.168.2.3", 139);
out = new PrintWriter(kkSocket.getOutputStream(), true); // Out may be used to write to server from the client
in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream())); // in will be used to read the lines sent by the Server.
}
catch (UnknownHostException e)
{
System.err.println("Unidentified host.");
System.exit(1);
}
catch (IOException e)
{
System.err.println("Couldn't get I/O for the connection to.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromClient;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("Bye"))
break;
fromClient = stdIn.readLine();
if (fromClient != null) {
System.out.println("Client: " + fromClient);
out.println(fromClient);
}
}
out.close();
in.close();
stdIn.close();
kkSocket.close();
}
}
I'm running the codes on eclipse in both the client and the server side. Using netstat -an command in cmd prompt, i can see that a connection has been established between the client and the server but i cannot communicate and eclipse is not showing any output too. What seems to be wrong??
You haven't told us what the problem is. However, from a cursory glance at your code, I would advise against listening on port 139 as this is already used by NetBios under Windows and may cause a conflict.
also your Server code is missing
the initialization of inputLine,
e.g
String inputline = "";
before the while loop
keep in mind that Socket's are blocked if you read or write...
your client is reading all the time because it waits for every information on the server
until it is null
and your server also reads all the time and is waiting for any input..
so as long as server and client are waiting for input, no one will receive any data.
try to think of a protocol to communicate between the server and the client.
e.g
Sever to Client: Hello Who are you?
Client receives Data and replies: Client
Server receives Information: You Are now authorized, what ya gonna do?
and so on ^^
also out.flush() is needed to send a message