Java - ServerSocket error - java

I'm attempting to receive a message from another computer, with a simple chat client.
I'm getting this error in the Console:
Starting Listener.......
Could not listen on that port
error: null
I get this in the Console when I send text over.
Here's my code
import java.io.*;
import java.net.*;
class TCPServer
{
public static void main(String argv[]) throws Exception
{
System.out.println("Starting Listener.......");
try{
ServerSocket welcomeSocket = new ServerSocket(5060);
while(true)
{
//
// Read a message sent by client application
//
Socket clientSocket = welcomeSocket.accept();
ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
String message = (String) ois.readObject();
System.out.println("Message Received: " + message);
}
}
catch (IOException e) {
System.out.println("Could not listen on that port");
System.out.println("error: "+e.getMessage());
System.exit(-1);
}
}
}
Can anyone see what I'm doing that's causing that null value? For that matter, what's causing the catch exception when I send a text string over.

Use System.out.println("error: "+e) to see the exception type which should provide more detail on what exactly went wrong - Java's class library exceptions are notorious for not including a message detailing the problem (and have only started getting better about this in recent releases).
Also, your catch of IOException will include any errors using the socket, including your attempt to read from a listen socket, so your error handling is misleading and insufficient.

Related

How can i keep a stream opened to receive data without closing the socket and waiting for client's data?

I'm programming in Java and i'm making a socket connection between server and several clients (using threads).
In the client side i made an opened Socket that connects to the server in a respective port and i send several objects, then the client disconnects.
In the server side i made a ServerSocket (where the client connects) and i use the accept() method to get the Socket, i don't want the socket to close so i keep it opened until i want (using a method for example), then i create an stream (ObjectInputStream) and read every object sent from the client, but i don't want it to close too. To continue the understanding of my problem here is the class i made:
import java.io.*;
import java.net.*;
public class ServerConnection implements Runnable{
private Socket connection;
public ServerConnection(Socket c){
connection = c;
}
#Override
public void run() {
// I used String i this example, but the real code use a Object sending system that i created
// because i needed to send different objects in one object (this ones implements Serializable).
String msg;
try {
ObjectInputStream inStream = new ObjectInputStream(connection.getInputStream());
do{
inStream.
msg = ((String)inStream.readObject());
System.out.println(msg);
}
while(!msg.equals("FINISH CONNECTION"));
} catch (IOException ex) {
System.err.println("run() - (io): "+ex.getMessage());
try {
connection.close();
} catch (IOException ex1) {
System.err.println("run() - (io/io): "+ex.getMessage());
}
} catch (ClassNotFoundException ex) {
System.err.println("run() - (classNF): "+ex.getMessage());
}
}
// The main method was created to make tests
// I'll use objects of this class to every client connection
public static void main(String[] args){
try {
ServerSocket server = new ServerSocket(8010);
Socket connection = server.accept();
ServerConnection svConnection = new ServerConnection(connection);
Thread theThread = new Thread(svConnection);
theThread .start();
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
}
This can receive the Strings i sent from the client, but the do-while isn't able to catch exceptions, the IOException is throwed when the Stream has no more Strings, so i want to prevent the throwing of that exception when the stream doesn't have more Strings to read, i tried to use recursive try-catch but i know that is not recommended. So there is another solution to this?
(Every answer is welcome. Thanks)
(EDIT)
For those one who needs the client code, so here it is:
import java.io.*;
import java.net.*;
public class ClientConnnection{
// There is a method that i don't make yet
public static void main(String[] args){
try {
Socket socketToServer = new Socket("localhost",8010);
ObjectOutputStream outStream = new ObjectOutputStream(socketToServer.getOutputStream());
outStream.writeObject(new Message("Hello :D"));
outStream.writeObject(new Message("How r u?"));
outStream.writeObject(new Message("Other message"));
outStream.flush();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}

Read data directly from /dev/log Unix Domain Socket

My project aims at reading log messages directly from /dev/log UNIX domain socket in Java. Currently I am using junixsocket. Below is a sample code of client that reads from a unix socket.
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.newsclub.net.unix.AFUNIXSocket;
import org.newsclub.net.unix.AFUNIXSocketAddress;
import org.newsclub.net.unix.AFUNIXSocketException;
public class SimpleTestClient {
public static void main(String[] args) throws IOException {
final File socketFile = new File("/dev/log");
AFUNIXSocket sock = AFUNIXSocket.newInstance();
try {
sock.connect(new AFUNIXSocketAddress(socketFile));
} catch (AFUNIXSocketException e) {
System.out.println("Cannot connect to server. Have you started it?\n");
System.out.flush();
throw e;
}
System.out.println("Connected");
InputStream is = sock.getInputStream();
byte[] buf = new byte[8192];
int read = is.read(buf);
System.out.println("Server says: " + new String(buf, 0, read));
is.close();
sock.close();
System.out.println("End of communication.");
}
}
The above mentioned code is unable to connect to /dev/log. It throws an exception:
Cannot connect to server. Have you started it?
Exception in thread "main" org.newsclub.net.unix.AFUNIXSocketException: Protocol wrong type for socket (socket: /dev/log)
at org.newsclub.net.unix.NativeUnixSocket.connect(Native Method)
at org.newsclub.net.unix.AFUNIXSocketImpl.connect(AFUNIXSocketImpl.java:125)
at org.newsclub.net.unix.AFUNIXSocket.connect(AFUNIXSocket.java:97)
at org.newsclub.net.unix.AFUNIXSocket.connect(AFUNIXSocket.java:87)
at SimpleTestClient.main(SimpleTestClient.java:40)
I am unable to figure out how to solve this problem. Any help would be appreciable.
Since you cannot connect to an existing server socket as mentioned in the log traces, then you haven't bound one one the mentioned file, so try creating an AF_UNIX server socket then connect to it.
It could be done in a separate class:
public class DevLogServer {
public static void main(String[] args) throws IOException {
final File socketFile = new File("/dev/log");
AFUNIXServerSocket server = AFUNIXServerSocket.newInstance();
try {
server.bind(new AFUNIXSocketAddress(socketFile));
} catch (Exception e) {
throw e;
}
}
}
Edit as per #Ankit comment:
You may also need to make sure the syslod daemon is stopped by runnig below command in a terminal window:
sudo service syslog stop
You may alternatively need to grand write permission to the /dev directory.

Java listen for server - messages getting lost

I am using a thread and a while true loop to listen for message from my server. For some strange reason some messages are getting lost. (I am logging from my server so i am 100% sure that the message is sent, therefore the problem has to be on the client side). This seems to happend when the server is sending messages fast to the client.
Im using the following code to listen for new messages (on my client):
Socket socket;
try {
socket = new Socket(InetAddress.getByName("url.com"), 8080);
is = new DataInputStream(socket.getInputStream());
os = new DataOutputStream(socket.getOutputStream());
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(rootPane,
"Could not establish network connection to the server."
+ " \nPlease check your internet connection and restart the application.",
"Unable to connect",
JOptionPane.INFORMATION_MESSAGE);
WindowEvent wev = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev);
setVisible(false);
dispose();
System.exit(0);
}
// Starta thread to listen for messages from the server
new ListenFromServer().start();
/*
* Thread class to listen for message from the server
*/
class ListenFromServer extends Thread {
public void run() {
while (true) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String tmpMsg = in.readLine().replaceAll("\\r\\n|\\r|\\n", "");
JSONObject json = new JSONObject(tmpMsg);
if(json.get("type").toString().contains("preview")) {
System.out.println("PREVIEW: " + json.get("msg").toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
You shouldn't be creating a new BufferedReader to receive each message. If two messages arrive in quick succession, it could pull multiple messages out of is, and then you're discarding the contents. Declare in outside of your while loop (and handle the close condition appropriately).
I think what you want is a ServerSocket -- it listens and handles a queue of incoming connections (default size 50) so that you don't lose connections. As your code is, if a connection is attempted in the time between one connection getting established and the loop coming around to connect() again, there wouldn't be anything listening.

Restart ServerSocket after IOException

How to restart ServerSocket after IOException?
My server socket sometimes gets an EOFException and then stops accepting new connections. To solve this I have tried closing the old server socket and creating a new one after the exception is thrown. However even after the new server socket is created, new connections are not accepted. Can some one see why this does not work?
public Server() throws IOException {
try {
listen(port);
}
catch (IOException e) {
System.out.println("Server() - IO exception");
System.out.println(e);
/*when an exception is caught I close the server socket and try opening it a new one */
serverSocket.close();
listen(port);
}
}
private void listen(int port) throws IOException {
serverIsListening = true;
serverSocket = new ServerSocket(port);
System.out.println("<Listening> Port: " + serverSocket);
while (serverIsListening) {
if (eofExceptionThrown){ //manually triggering an exception to troubleshoot
serverIsListening = false;
throw new EOFException();
}
//accept the next incoming connection
Socket socket = serverSocket.accept();
System.out.println("[New Conn] " + socket);
ObjectOutputStream oOut = new ObjectOutputStream(socket.getOutputStream());
// Save the streams
socketToOutputStreams.put(socket, oOut);
// Create a new thread for this connection, and put it in the hash table
socketToServerThread.put(socket, new ServerThread(this, socket));
}
}
2x entry point , one form catch: never ends well.
try {
listen(port);
}
catch (IOException e) {
System.out.println("Server() - IO exception");
System.out.println(e);
/*when an exception is caught I close the server socket and try opening it a new one */
serverSocket.close();
listen(port);
}
I would do in a loop, while a boolean is true:
while(needToListen){
try{
listen(port)
}catch(Exception ex){
if(exception is what needed to break the loop, like a message has a string on it){
break;
}
}
}
if(needToListen){
Log.e("something unexpected, unrecoverable....");
}
My server socket sometimes gets an EOFException and then stops accepting new connections
No it doesn't. ServerSockets never get EOFExceptions. Rather, one of your accepted Sockets is getting an EOFException, which is only to be expected, and you are closing both that Socket, which is correct, and the ServerSocket, which is incorrect. Exceptions on accepted sockets don't affect the listening socket.

Listen to port via a Java socket

A server software my client communicates with regularly sends transaction messages on port 4000. I need to print those messages to the console line by line. (Eventually I will have to write those values to a table, but I’m saving that for later.)
I tried this code but it doesn’t output anything:
package merchanttransaction;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class MerchantTransaction {
public static void main(String[] args) {
try {
InetAddress host = InetAddress.getLocalHost();
Socket socket = new Socket("192.168.1.104", 4000);
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
System.out.println("Message: " + message);
ois.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
By the way, I need to be able to monitor that port until the program terminates. I’m not sure if the code above will be able to do that because I don’t see any iteration to the code.
I’m using Java version 1.6.0_24, SE Runtime Environment (build 1.6.0_24-b07) running on Ubuntu.
You need to use a ServerSocket. You can find an explanation here.
What do you actually want to achieve? What your code does is it tries to connect to a server located at 192.168.1.104:4000. Is this the address of a server that sends the messages (because this looks like a client-side code)? If I run fake server locally:
$ nc -l 4000
...and change socket address to localhost:4000, it will work and try to read something from nc-created server.
What you probably want is to create a ServerSocket and listen on it:
ServerSocket serverSocket = new ServerSocket(4000);
Socket socket = serverSocket.accept();
The second line will block until some other piece of software connects to your machine on port 4000. Then you can read from the returned socket. Look at this tutorial, this is actually a very broad topic (threading, protocols...)
Try this piece of code, rather than ObjectInputStream.
BufferedReader in = new BufferedReader (new InputStreamReader (socket.getInputStream ()));
while (true)
{
String cominginText = "";
try
{
cominginText = in.readLine ();
System.out.println (cominginText);
}
catch (IOException e)
{
//error ("System: " + "Connection to server lost!");
System.exit (1);
break;
}
}

Categories