Chat server and client Implementation - java

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

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.

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.

Use Java to connect ethernet device

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.

Android Java Socket - Connection timed out

I'm trying to create one simple app. I want to my cell phone be a server socket and I'm trying to send messages from my pc, my pc is the client is this case.
When they are in the same network it works fine but when I connect my cell phone in a 3G network I receive the error "Connection timed out" in my PC.
I'm using a host from no-ip (in both situation). When I do 'telnet mycellphonehost.org 8080' for example I have no problem, it is able to connect. I think the no-ip host is working fine because is give me the correct external IP.
I also use one app called FIREBIND for test if the port is open or not. The result is: "Firebind was successfully able to both transmit and receive data over this port using the TCP protocol."
I already read a lot questions about this subject, similar problems... but nothing help me solve this issue. I hope someone can help me. Thanks in advance!
Follow the codes:
Android Server
try{
ServerSocket server = new ServerSocket(port);
Socket s = server.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println(input.readLine());
input.close();
s.close();
server.close();
}
catch(IOException e){
System.out.println("ERROR: " + e.getMessage());
}
PC Client
try{
Socket s = new Socket("myhostfromno-ip.org",port);
PrintStream output = new PrintStream(s.getOutputStream());
output.println("TEST MESSAGE");
output.flush();
s.close();
}
catch(IOException e){
System.out.println("ERROR: " + e.getMessage());
}
PS: They have to be in different network
I would recommend using GCM for the cell
Notification and afterwards making a server pull. It certainly is much faster and you could use a simple REST server for serving data.
You need to make your PC the server and your droid the client.

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 .

Categories