Java: How send and receive data using socket? - java

I'm building a middleware, where I need to constantly read what is happening in my device, so I build this class:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
/**
*
* #author Valter
*/
public class Middleware {
public static void main(String args[]) {
try {
// ip and port where is my device
Socket socket = new Socket("192.168.1.4", 2001);
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
// i need send this parameter to my device
dataOutputStream.writeUTF("}Rv!");
String answer = dataInputStream.readUTF();
System.out.println("Answer:"+answer);
dataInputStream.close();
dataOutputStream.close();
socket.close();
} catch (UnknownHostException ex) {
System.out.println("UNKNOW HOST EXCEPTION");
} catch (IOException ex) {
System.out.println(" IOEXCEPTION");
System.out.println(ex.getMessage());
}
}
}
Output:
IOEXCEPTION Connection reset
What's wrong with my class?

I don't know if this is what is causing your problem, but you are not flushing the output stream before attempting to read a response from the input stream. Try:
dataOutputStream.writeUTF("}Rv!");
dataOutputStream.flush();

Does your device really understand the output of writeUTF()?and produce the correct input for readUTF()? Check the Javadoc. I don't think it likely.
'Connection reset' usually means you have written to a connection that was already closed by the other end, which is already an application protocol error, and it may indicate prior application protocol errors.

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.

Copy a Different Program's Local Server (Java)

First off, networking is not my strongest subject. So sorry if this question is ridiculous, or if I'm missing some major information. I'd be happy to provide any needed.
I am trying spoof a server program. The program I am trying to pretend to be basically creates a local server, then allows client versions of the same program to connect (provided they are on the same computer).
Using netstat -a -b -n I was able to figure out that the server was binding itself to 0.0.0.0:53640. The other information given was:
Proto: UDP
Local Address: 0.0.0.0:56426
Foreign Address: * : * (Without spaces, stackoverflow doesn't seem to like this when it doesn't have them)
State: (Was blank)
The closest I was able to come was
Proto: TCP
Local Address: 0.0.0.0:56426
Foreign Address: 0.0.0.0:0
State: LISTENING
The code that I am using is:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class Main2
{
public static void main(String args[])
{
String ip = "0.0.0.0";
int port = 53640;
try
{
InetAddress address = InetAddress.getByName(ip);
ServerSocket server = new ServerSocket(port, 5, address);
System.out.println("Waiting for connection...");
Socket socket = server.accept();
System.out.println("Got connection!");
doSocket(socket);
server.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void doSocket(Socket socket)
{
try
{
System.out.println("Connection from: " + socket.getInetAddress());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream());
int b;
char c;
while ((b = in.read()) != -1)
{
c = (char) b;
System.out.print(c);
}
in.close();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
ServerSocket.accept seems to never stop yielding, as "Got connection!" is never printed to the output.
All help is very welcome. Thanks in advance! And sorry if I've done something horribly wrong with this post, its my first one.
UDP is connection-less, and 'ServerSocket' is connection-oriented and TCP-only. Have a look at the Oracle docs on datagrams (UDP).
UDP ports and TCP ports are in different namespaces; you can't get mixups from one to the other.

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;
}
}

Help me to fix a bug in this thread example

I am trying to create a thread to simply send the text to client. However, if you copy this code to IDE, you will see that there is a red underline under client.getOutputStream(). I do not know what is wrong here. The IDE says "Unhandled exception type IOException". Could anybody tell me?
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class ServerStudentThread extends Thread {
Socket client;
public ServerStudentThread(Socket x) {
client = x;
}
public void run() {
// create object to send information to client
PrintWriter out = new PrintWriter(client.getOutputStream(),true);
out.println("Student name: ");//send text to client;
}
}
For reference, here is the code that calls the thread.
import java.io.*;
import java.net.*;
import java.util.*;
public class Server2 {
public static void main(String args[]) throws Exception {
int PORT = 5555; // Open port 5555
//open socket to listen
ServerSocket server = new ServerSocket(PORT);
Socket client = null;
while (true) {
System.out.println("Waiting for client...");
// open client socket to accept connection
client = server.accept();
System.out.println(client.getInetAddress()+" contacted ");
System.out.println("Creating thread to serve request");
ServerStudentThread student = new ServerStudentThread(client);
student.start();
}
}
}
It's probably that getOutputStream() can throw an exception and you're not catching it, try putting a try / catch (IOException e) around the block of code.
public void run() {
try {
// create object to send information to client
PrintWriter out = new PrintWriter(client.getOutputStream(),true);
out.println("Student name: ");//send text to client;
} catch (IOException e) {
throw new RuntimeException("It all went horribly wrong!", e);
}
}
So you need to add a try/catch block to handle the I/O exception.
Read the section on Exceptions from the Java tutorial.
From the javadoc:
public OutputStream getOutputStream() throws IOException
IOException is a checked exception. You need to use a try/catch block to handle that possibility.
Kalla,
You need to either put the line in between try/catch block or declare run to throw IOException

Categories