Use Java to connect ethernet device - java

I had a board connect to the PC using LAN cable(RJ45). I need to write the Java code to connect the board and get some data from it. How can I do it?
Actually I got a code from C++, it used CAsyncSocket class to do it. The C++ code is like this:
CAsyncSocket.Create();
CAsyncSocket.connect(IP, PORT);
Now, I would like to convert it into Java. Actually, I'm not so familiar with Java. Can someone show the code to me?
Example: My board IP is 192.168.2.10 and PORT is 2000. How can I connect it using Java?

see here (for example):
Socket socket = new Socket("192.168.2.10", 2000);
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("Input: " + input.readLine());
socket.close();
http://docs.oracle.com/javase/7/docs/api/java/net/Socket.html

Check out the socket tutorial Lesson: All About Sockets:
URLs and URLConnections provide a relatively high-level mechanism for accessing resources on the Internet. Sometimes your programs require lower-level network communication, for example, when you want to write a client-server application.
See the [http://docs.oracle.com/javase/tutorial/networking/sockets/readingWriting.html](Reading from and Writing to a Socket) example:
Let's look at a simple example that illustrates how a program can establish a connection to a server program using the Socket class and then, how the client can send data to and receive data from the server through the socket.

Related

Java Socket Packet Interception

I'm trying to write a socket program in Java that intercepts data/packets.
I've successfully written this in python:
import socket
def createListener(port):
srvSock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
srvSock.bind(('localhost', port))
srvSock.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
while True:
raw_data, addr = srvSock.recvfrom(65536)
print('data: ' , raw_data)
createListener(80)
This is my basic Java socket program
public static void main(String[] args) {
try{
ServerSocket ss = new ServerSocket(80);
Socket s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
String str = (String)dis.readUTF();
System.out.println("data: "+str);
ss.close();
} catch(IOException i){
System.out.println(i);
}
}
However, when run, it doesn't intercept all data moving through the port on the network like the python program does. Specifically this line srvSock.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) in the Python script enables the socket to listen to the port and capture/intercept the entirety of the data going through it.
I cannot find a Java alternative to this syntax or any solution to my problem at all for that matter.
I would appreciate any help in how to use sockets to intercept packets on a network port.
Thanks
Im fairly certain what you are trying to do cannot be done with Java. It looks like you are trying to use "promiscuous mode", but Java sockets cannot be started in promiscuous mode. Java sockets are an end-to-end implementation: they can't listen on the network port for all traffic. For sure the network port would have to be in promiscuous mode, but I don't think Java is the right choice for you.
The only thing I can think of that might get you there would be doing a native call in something like JNI, but I wouldn't even really know where to start with that.
Here is a really old post that I found that is kind of related: java socket and web programing
From the looks of it, you're trying to read incoming bytearrays as string lines.
If that is so, this is what I do to read lines without missing a single line (In Kotlin):
socket.getInputStream().bufferedReader(Charsets.UTF_8).forEachLine {
it -> { /* Do what you wanna do with the input */ }
}
In Java, it's much less abstract :
BufferedReader(InputStreamReader(socket.getInputStream(), Charsets.UTF_8), 8 * 1024)
Then, use lines from this buffered reader as a line sequence to read your incoming lines.

Chat server and client Implementation

I want to Implement a Chat Server and Client using java like gTalk, what Type of connection should i work on(XAMPP or Socket Connection), please guide me, i want to implement this for my final sem project.It will be a kind of Instant Messaging like gTalk and skype.
Please give me some idea/outlines or links where i can read some stuff, so that i can study some and start implementing those.
try {
Socket skt = new Socket("localhost", 1234);
BufferedReader in = new BufferedReader(new
InputStreamReader(skt.getInputStream()));
System.out.print("Received string: '");
while (!in.ready()) {}
System.out.println(in.readLine()); // Read one line and output it
System.out.print("'\n");
in.close();
}
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
}
Thanks
XAMPP is mostly a package of software mainly Apache webserver, MySQL, Perl and PHP.
Since you want to code in java, the chat server would be based on Socket Programming.
As per the code snippet you have posted is a simple java server, which can listen to request and print on screen what's been send to it.
On doing some google search found a simple step by step explanation of creating chat application in java.
http://pirate.shu.edu/~wachsmut/Teaching/CSAS2214/Virtual/Lectures/chat-client-server.html

Java TCP Client/Server

I have a problem which I do not know how to proceed further in Java TCP socket issue. So far as what we can get from the Internet, it's not hard to get quite a number of working solution for TCP server & client communication in Java. However, most of the example will have their server listen to a port, and then loop until they get a client which connects to the server, then the code will perform server.accept() and move further. For example:
public static void main(String[] args) throws IOException {
ServerSocket s = new ServerSocket(PORT);
System.out.println("Started: " + s);
try {
// Blocks until a connection occurs:
Socket socket = s.accept();
try {
System.out.println("Connection accepted: "+ socket);
It will work perfectly if there's a client connecting to the server. And, my problem is that I need to continue some other procedures even though there's no client connecting to the server. In fact, I will need to launch another JFrame to continue the procedures even if there is no client connecting to the same port and ip. However, I have been struggling but as long as there is not client connecting to the server, my Java program will hang there with white popped up JFrame.
I would need to know how to overcome this as I am not quite sure whether there's a mistake in my understanding. Please assist and advice. Thank you!
Best Regards,
Yi Ying
Sounds like you need to do work in one thread whilst waiting for network connections on another. Check out the threading tutorial. Note that since you're using Swing, you have to be careful wrt. which thread will modify your JFrame etc. and you should be aware of the SwingWorker utility.

How can I modify this code to allow my client socket program to send a string to the server?

Hi ive written some code to connect to a server through the use of a socket. Id like to write some simple code that allows me to send a string to the server, im assuming this will involve input and output streams but I am new to this. Ive put the code I am working with below, any insights into the best way to accomplish this would be great.
import java.net.*;
import java.io.*;
public class SocketMarket
{
public static void main(String [] args)
{
String serverName = "XX.X.X.XXX";
int port = XXXX;
try
{
System.out.println("Connecting to " + serverName + " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Connected to " + client.getRemoteSocketAddress());
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Thanks in advance
client.getOutputStream().write("Hello World".getBytes());
client.getOutputStream().flush();
The above is how you would send just a String, but you will probably want to build up some infrastructure around sending arbitrary text.
The general idea is that your server and client will communicate with each other using InputStream's and OutputStream's, which can be accessed from a Socket via getInputStream() and getOutputStream(), once the connection between them is made.
For your server to receive connections, you should be using a ServerSocket to accept() incoming connections.
Insight is here, the "really big index" for java.
http://docs.oracle.com/javase/tutorial/networking/sockets/readingWriting.html
Yes, it involves OutputStreams. If you want to output Strings you could write raw bytes via the OutputStream you get from the connection but then you completely loose control over encoding. You need to learn about reader/writer/streams first, then networking via sockets is simple. You can find the relevant part of the Java tutorials here: http://docs.oracle.com/javase/tutorial/essential/io/ (you can ignore the NIO part completely for the beginning). After that you can learn about socket networking: http://docs.oracle.com/javase/tutorial/networking/sockets/index.html .

Communication between java server and matlab client

I'd like to establish a server(Java)/client (Matlab) communication using socket. They can send messages to each other. An example shows how to do this in Java server and Java client, http://java.sun.com/docs/books/tutorial/networking/sockets/clientServer.html.
When I try to rewrite the client part in Matlab, I only can get the first message that the Java server sends and display it in the Matlab command window.
When I type a message in the Matlab command window, I can't pass it to the Java Server.
Jave code:
kkSocket = new Socket("localhost", 3434);
Matlab equivalent:
kkSocket = Socket('localhost', 3434);
Java code for client:
out = new PrintWriter(kkSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
What would be a Matlab equivalent for this? Thanks in advance.
For the input stream:
input_stream = input_socket.getInputStream;
d_input_stream = DataInputStream(input_stream);
For the output stream:
output_stream = output_socket.getOutputStream;
d_output_stream = DataOutputStream(output_stream);
If you are trying to use MATLAB and the Java application on the same machine then matlabcontrol may do everything that you are looking for. It automatically establishes a connection to a session of MATLAB. It uses Java's Remote Method Invocation under the hood which makes use of sockets. matlabcontrol is designed specifically to only enable communication on localhost; the sockets it creates will not accept remote connections due to the security issues that could allow. However, if you need to allow remote connections you may find parts of matlabcontrol's source code to be useful.

Categories