send stringt from android over wifi and recieve in PC(java program) - java

I want to make simple android app in which i simply have textview, and a button. on clicking that button, string in textview is broadcast and received at PC. am new to android programming and network programming.
1. Please suggest what tool to be used in PC.
2. Some simple steps to achieve this.
3. some healthy tutorials to understand things better.
Sorry if i sound stupid :P
Thanks in advance.

Welcome to StackOverflow!
Well it sounds like you want to jump into the world of programming Android head first. That's fine but you should start somewhere. The best series of tutorials I've seen to date is at The New Boston. The videos are very easy to understand and the series is made of 200 videos. It covers everything from downloading and installing Eclipse (which is one tool you can use to develop Android apps) all the way to some pretty advanced concepts. So if you have a basic understanding you can pick and choose which videos you want to watch, if you want a full crash course just watch them all. It also has around 3000 other videos on all programming languages. Such as Java which you will need if you don't already know.
On the P.C. side if you don't have any live servers set up to play with I suggest downloading XAMPP at this link XAMPP. It allows you to create a number of things on your own computer, all of which are free. Such as a SQL database with phpmyadmin and a number of other things. All in all if you watch even a few of the 200 videos at The New Boston you will have a much better understanding of what you need to do to accomplish your goals. You will also have a better understanding of what to ask for specifically in the future. Hope this helps, if you need anything else just ask

Well, i'm not sure if this is the best way but still is a way, you could use SMB for android, and for the PC just a normal Java program so:
1: for PC you could use Java (since you use Java as a topic i supose that you know how to do a single program with this programming language
as a suggestion for achieve number 1, you could do a program that every 3-5 seconds constantly check if a empty File have data or still empty and if it has data then show a Dialog with the data, a showMessageDialog would do the job.
2: for android use what i said first, with that you could read or write a File on the PC from your android device, of course if both the PC and android device are in the same network
at this point, just write the String of the TextView or EditText in the File on the PC being checked by the java program, let me know if this help you or if you want more specific details, but i think with this you could do what you want. Sorry for my English, still learning it :)

It sounds like sockets would be good for what you want to do.Basically, you'll need to have a server script/program running on the PC and the android program can send a connection request and then a packet with the string.
You'll need to create a ServerSocket with something like this on the server and have it listen on a port of your choosing.
ServerSocket serverSocket = null;
int port = 9876;
try {
serverSocket = new ServerSocket(port);
} catch ( Exception e ) {
System.out.printf("Could not listen on port: %d", port );
System.exit(-1);
}
Often a new thread is used to accept the connection like this.
new Thread(new ServerThread(serverSocket.accept())).start();
The run() method of the ServerThread can be as simple as this
try {
Scanner socketIn = new Scanner(this.clientSocket.getInputStream());
PrintWriter socketOut = new
PrintWriter(this.clientSocket.getOutputStream(), true);
while(socketIn.hasNext() {
System.out.println(socketIn.next());
}
} catch (Exception e) {
}
You can create a socket on the client side (in your case on the android device) with code like this. (Note that android won't let you do this in your main thread so you'll have to create the connection in another thread.
public void sendRequest(final String message) {
Log.d("test", "log");
new Thread() {
#Override
public void run() {
try {
Socket socket = new Socket(InetAddress.getByName(HOST), PORT);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(message);
} catch (Exception e) {
Log.d("Exception in thread", e.getStackTrace()+"");
}
}
}.start();
}
Since you're just doing this on your wifi, instead of InetAddress.getByName(HOST), you can just put the local IP address of the PC. Also, if you are planning on this working always, rather than just learning and practicing around, it would be good to set up the PC with a static local IP on your network. There are plenty of tutorials for doing that on different OSs out there.
Fortunately, socket programming in java is pretty simple. You can use the Scanner and Printwriter to read and write to sockets.
Please note that I have not tested the above code, but the principle is sound.
Here are a few sites with some info.
http://cs.lmu.edu/~ray/notes/javanetexamples/
http://docs.oracle.com/javase/tutorial/networking/sockets/ I like this one
Edit. I could only post two of the links because my rep is low.

Related

How to make a local multiplayer java game runs online?

I've developed a decent amount of multiplayer games lately in java (board/turn based games running on a tcp connection with data in/out streams) but they only work locally, I want to go a step further and make them run online, what do I need to change to make it work?
It seems like there are many ways to accomplish that yet i don't know where to start, as I don't know much about networking.
Besides that I don't have a real server, I'm only using my home router and my pc.
So here is what I've tried so far:
I enabled port forwarding in my router and I think it works (I used a port forwarding checking tool online)
I created a dynamic DNS for my public ip using noip.com
So the server side should be fine at least, my problem is with the client side, the client's socket won't connect to my public ip, when I searched for a solution I concluded that the client shouldn't be in the same LAN where the server is, so I used a mobile hotspot as a second network and tried again, but got the same results. (connection refused exception)
is it because of the mobile hotspot (should I use another router) ?
or is it just some coding tweaks ?
This is a minimal server class example
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(50895);
Socket cs = ss.accept();
DataOutputStream out = new DataOutputStream(cs.getOutputStream());
DataInputStream in = new DataInputStream(cs.getInputStream());
out.writeInt(123456);
} catch (IOException e) {
e.printStackTrace();
}
}
And this a minimal client class example
public static void main(String[] args) {
try {
String ip = Inet4Address.getByName("my Dynamic IP address").getCanonicalHostName();
System.out.println(ip);
InetSocketAddress sa = new InetSocketAddress(ip, 50895);
Socket cs = new Socket();
cs.connect(sa);
DataOutputStream out = new DataOutputStream(cs.getOutputStream());
DataInputStream in = new DataInputStream(cs.getInputStream());
System.out.println("received : " + in.readInt());
} catch (IOException e) {
e.printStackTrace();
}
}
The method that i've tried always gives me a connection refused exception, so any solution would be appreciated.
I found a software solution to the problem through virtual lan (using LogMeIn Hamachi) which is basicly used for creating game servers, you just need to create an account and a network so your friends can join it, after that everything should be fine and runs as if it's locally hosted.
You can download the software through here but there are many alternatives to choose from, that one gives you up to 5 people on the network for free, it's not the best, but still a free solution.
I still want more of a java solution to this problem that doesn't require a third-party software.

How could I sniff network traffic in Java?

I was just looking around to find out how to make a program that would sniff my network traffic in Java, but I couldn't find anything. I wanted to know if there was any way to view the network traffic going by. I heard of an idea with a Socket, but I don't get how that would work. So anyways, just looking for an API or a way to write it myself.
EDIT:
I would gladly like an API, but I would also like clarification on the way to sniff traffic with a Socket.
jpcap, jNetPcap -- those are pcap wrapper projects in Java.
Kraken -- similar project, well documented with lots of examples.
simple example from the Kraken web site:
public static void main(String[] args) throws Exception {
File f = new File("sample.pcap");
EthernetDecoder eth = new EthernetDecoder();
IpDecoder ip = new IpDecoder();
TcpDecoder tcp = new TcpDecoder(new TcpPortProtocolMapper());
UdpDecoder udp = new UdpDecoder(new UdpPortProtocolMapper());
eth.register(EthernetType.IPV4, ip);
ip.register(InternetProtocol.TCP, tcp);
ip.register(InternetProtocol.UDP, udp);
PcapInputStream is = new PcapFileInputStream(f);
while (true) {
// getPacket() will throws EOFException and you should call is.close()
PcapPacket packet = is.getPacket();
eth.decode(packet);
}
}
Another Java libpcap wrapper is https://github.com/kaitoy/pcap4j
Pcap4J is a Java library for capturing, crafting and sending packets. Pcap4J wraps a native packet capture library (libpcap or WinPcap) via JNA and provides you Java-Oriented APIs.
You need a packet sniffer api, maybe netutils is what you need:
The 'netutils' package gives a low level java network library. It
contains extensive infrastructure for sniffing, injecting, building
and parsing Ethernet/IP/TCP/UDP/ICMP packets.
Not telling any API or java related thing but if you really want to only sniff data for analysis purpose then give try: WireShark. Its an application used for network analyse.
Its useful if someone is not aware of.

How to test connectivity to ports

I'm still a beginning programmer but I like to experiment and learn while practicing. I play League of Legends a lot, this is the biggest online game today. Sometimes the server of this game are offline and my idea was to make a java programm that checks wether the game is online (ports are open) and then tells me if the game is online or not. Due to me being a beginner programmer and my understanding of ports/network adresses still lack a bit, I wonder if someone could explain or help me achieving my goal. If it is by explaining or providing helpfull links, I'm open to everything!
Thanks in advance,
Boris
There are some tools that you can check that whether the server is alive or not.
The most basic one is ping in CMD:
ping stackoverflow.com (if you have domain)
or
ping 198.252.206.16 (if you have IP)
if you see sth like this so server is alive and give a response:
Ping statistics for 198.252.206.16:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 142ms, Maximum = 145ms, Average = 143ms
But if you see this, then server or your internet connection has a problem:
Request timed out.
There are some other tools such as Hercules to test a server alive or not.
If you are still sure to write a program yourself in java, you can try to create a new java.net.Socket. If that line throws any exception then you are not able to connect to the server. To manage this, you should use "try-catch" blocks.
You can use java socket to detect the port is alive or dead:
import java.io.IOException;
import java.net.Socket;
public class PortDetect {
public static void main(String[] args) {
try {
new Socket("1.2.3.4", 8080);
System.out.println("alive");
} catch (IOException e) {
e.printStackTrace();
System.out.println("dead");
}
}
}

Socket communication between Android app and web browser

My Android device+app is continuously sending data every few ms, and I'd like to receive it on my web browser application that I'm building with JavaScript/HTML.
In the Android/Java app I do the following over socket:
//Initialize, where PORT = local ip of my laptop with web server I guess.
//and I choose an available port on my network, say 8080.
echoSocket = new Socket(HOST, PORT);
out = new PrintWriter(echoSocket.getOutputStream(), true);
//Sending data every few ms:
JSONObject j = new JSONObject();
j.put("x", params[0]);
j.put("y", params[1]);
j.put("z", params[2]);
String jString = j.toString();
out.println(jString);
So I have something like {"x": 1.0023532, "y": 2.454234, "z": 6.234583}.
In other Java applications, I've done this communication by having my receiver application create a ServerSocket on the particular PORT used above. Then as long as I have the right local IP address for my laptop, I can do serverSocket = new ServerSocket(PORT); etc.
Now, how can I accept this data in a web application (JavaScript/HTML)? I've heard of websockets but have no idea how to initialize and use for this purpose - hopefully it's pretty straightforward.
I dont think its possible to send data directly to the browser without a middle man (server). If you want to create a fast and easy server to ping data back and forth I would have some fun with NodeJs. I havent gotten a chance to ever use the stuff but I did have some fun playing with it. It could be something to look into expecially if your just pinging data back and forth between clients.
I watched this video "Introduction to Node.js with Ryan Dahl" a while ago and he showed a basic example that does pretty much what your talking about. Just a thought, plus it would be a fun and fast implementation.
On a side note I do believe Amazon AWS has a instance for Node JS if you want to bring it to a live server. Im pretty sure you can setup a micro instance for no cost.

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.

Categories