I am new in Socket programming of java, i had written two files in Java named Server.java and Client.java as below:
Server.java
import java.io.*;
import java.net.*;
public class Server
{
static ServerSocket server = null;
static Socket socket = null;
static int userConnected=0;
static String msg = "In Server";
public static void main(String []args)throws Exception
{
int port = 1234;
server = new ServerSocket(port);
PrintStream output = null;
while(true)
{
socket=server.accept();
//Connection Arrived
userConnected++;
System.out.println("A new user arrived,\nNo. of user connected "+(userConnected));
}
}
}
Client.java
import java.net.*;
import java.io.*;
public class Client
{
static Socket socket = null;
public static void main(String[] args) throws Exception
{
socket = new Socket("localhost",1234);
}
}
When running Server class file on one system it will create Server on Port 1234 and when i run client class file it get successfully connected to Server on port 1234 and when i run another Client class file by another Console it also get connected to Server on port 1234,
What i want is to perform message passing between these two clients i.e. the message written in first client get shown in second client and vise-versa.
Can anyone please help me ??
http://www.tutorialspoint.com/java/java_networking.htm
I suggest you take a look at this. You can take a horse to the water, but cannot make it drink!
Check out ObjectOutputStream and ObjectInputStream in the standard Java API, you can then send Strings (and any other objects you want).
Related
I know it may be a stupid question but I am newbie in Java.
I need to host a small java app that uses DatagramSocket to listen to a port.
Usually to activate this code in a development environment a simple run of the java file and it listens to the port.
Usually, a java app that implements servlets is run in a Java container like Tomcat.
So, what should I do in my case to run this code in a production environment on the server?
import java.io.*;
import java.net.*;
class ServeurEcho
{
final static int port = 8532;
final static int size = 1024;
final static byte buffer[] = new byte[size];
public static void main(String argv[]) throws Exception
{
DatagramSocket socket = new DatagramSocket(port);
while(true)
{
DatagramPacket data = new DatagramPacket(buffer,buffer.length);
socket.receive(data);
doSomething(data);
}
}
public static void doSomething(DatagramPacket data) {
// ...
}
}
The code is a simple program to send stuff from one computer to the other. It works if the client and server are connected to different networks, but won't work when its the same network. (port forwarding is enabled for all the ports in use)
This is for a different program which works kinda like a blockchain. I'm not sure if its a router problem. My guess is that the port forwarding won't work internally between the network clients, which would seem like a router problem. HELP!
Client Side:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception{
String ipaddress = "70.121.56.92";
DatagramSocket reciever = new DatagramSocket(3535);
DatagramPacket pacc = new DatagramPacket(new byte[98],98);
Scanner s = new Scanner(System.in);
if (s.nextLine().equals("0")) {
reciever.receive(pacc);
System.out.println(Arrays.toString(pacc.getData()));
}
}
}
Server Side:
import java.net.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception{
Scanner kb=new Scanner(System.in);
DatagramSocket me=new DatagramSocket(3537);
String msg="";
while(!msg.equals("stop")){
System.out.print("msg: ");
msg=kb.nextLine();
byte[] bs=new byte[msg.length()];
for(int i=0; i <msg.length(); ++i){
bs[i] = (byte) msg.charAt(i);
}
DatagramPacket dgp=new DatagramPacket(bs, bs.length, InetAddress.getByName("70.121.**.9*"//this is my public router address), 3535 );
me.send(dgp);
}
}
}
On a different network it shows the string i put in the client on the server console. On the same network, it gets stuck inside the reciever.recieve() method
The router routes packets received on its WAN connection to computers on the LAN, perhaps using the port-forwarding mechanism. If you send from the LAN to the WAN address, which your server is doing, then it's pretty likely that the router isn't "folding back" that address into the LAN through the port-forwarding mechanism.
You can easily validate this by having the server send to the actual LAN address of the client computer.
I don't think this is a router defect; I think that's just the way it is with NAT.
I'm having trouble interpreting a question for a college assignment. It seems my solution is not an acceptable answer. I'm not looking for the solution just mainly an explanation on what I'm doing wrong.
The question is:
Implement a simple chat client which transmits user messages to a multicast address and receives messages sent from other clients on other machines sent to the same multicast address.
The way I am interpreting this is that I have is a server class with a multicast address, then n-amount of client classes that connect or join the server group.
Then when the client has connected to the server class. The server sends the same typed message out to the multiple clients which is displayed on screen of the client. Am I way off with whats asked??. My code for the multicast server is,
package multicastchatter;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class multicastServer {
final static String INet_addr = "224.0.0.3";
final static int PORT = 8888;
public static void main(String[] args) throws InterruptedException, UnknownHostException {
InetAddress addr = InetAddress.getByName(INet_addr);
try(DatagramSocket serverSocket = new DatagramSocket())//open the datagram
{
for(int i = 0; i<5; i++)
{
String message = "Sent message number "+i;
//create a packet and send
DatagramPacket messPack = new DatagramPacket(message.getBytes(),message.getBytes().length, addr, PORT);
serverSocket.send(messPack);
System.out.println("The server says"+ message);
Thread.sleep(500);
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
and my multicast client is
package multicastchatter;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
public class multicastClient {
final static String INet_addr = "224.0.0.3";
final static int PORT = 8888;
//final static int PORT = 8080;
public static void main(String[] args) throws UnknownHostException {
InetAddress address = InetAddress.getByName(INet_addr);//get address
byte[] buf = new byte[256];//create a buffer of bytes
//create the multicast socket
try(MulticastSocket clientSocket = new MulticastSocket(PORT))
{
clientSocket.joinGroup(address);//join the group
while(true)
{//recieve the info
DatagramPacket messPack = new DatagramPacket(buf, buf.length);
clientSocket.receive(messPack);
String message = new String(buf, 0, buf.length);
System.out.println("Socket recieved message saying" + message+ " by "+ messPack.getAddress());
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Any advice is appreciated. All I can think off is that I need to send messages back to the server from the client?
Being that your question is asking if your conceptualization of the client-server architecture is correct, then yes. What your teacher wants is a server that accepts client connections, and broadcasts client messages it receives to all clients.
A multi-threaded server approach is typically chosen in this situation, as many concurrent connections are being utilized, and each of them waits for a message. Upon receiving the message, the server will take that message, append an identifier to the front so that we know what client said the message, and distribute that message once only to each client.
As for the client, it just takes input, sending when necessary, and always listens for packets from the server, displaying whatever it receives. A valuable word of advice:
Do not allow the client side to display what is sent until it is received. In other words, sending input from the client program should only display what was sent when it is received back from the server. It is a good practice to employ in server-client architecture in most instances.
I read some materials about ServerSocket and tried to listen on port 80 and print for example InetAddress of website which I was opening in web browser but my program couldn't do this. My code:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Site implements Runnable {
private int port;
Site(int port){
this.port = port;
}
public void run() {
try {
ServerSocket server = new ServerSocket(port);
while(true){
Socket socket = server.accept();
System.out.println(socket.getInetAddress());
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String args[]){
Thread thread = new Thread(new Site(80));
thread.start();
}
}
When I run my program I am only one time in the while loop and the program doesn't print System.out.println(socket.getInetAddress()) and as the result when I open my web browser and visit http sites I don't see any output. Do you know what I am doing wrong? Do you know any other ways to print InetAddress for currently open website? Any materials will by appreciate.
I can't comment without proper reputation so forgive me for throwing everything out here:
you might already have something listening on port 80
you might be running on a version of linux that restricts non root process binding to ports above 1024
you might be blocked by a software firewall
I was wondering if i could get help making or finding a program that has the ability to send keyboard presses and receive them on another computer. I want to use this to play multiplayer flash-player games with friends across computers. I know there are some programs out there like "logmein" but both users cannot use the keyboard at the same time. (When i press a key the computer user cannot press a key at the same time because it wont respond.) I only know java and I am quite novice at it. Im guessing if i need to write it ill have to send the information through a port or onto a web-server. I would like to know your opinions and suggestions for this program, thanks guys.
Basically what you are looking for is a chatroom program? Have you tried looking into mIRC?
mIRC is a free internet relay chat. What exactly are the requirements for the program? Is there a certain size that it must be? Are these flash games that you and your friends are playing taking up your full computer screen?
Building a program would require a web-server(any computer with internet access would do), and you would have to open the ports on your network to allow the traffic to go through.
A basic server in java would look something like this:
Please note that after the first connection this "server" will close the connection.
import java.net.ServerSocket;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Server
{
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static BufferedReader bufferedReader;
private static String inputLine;
public static void main(String[] args)
{
// Wait for client to connect on 63400
try
{
serverSocket = new ServerSocket(63400);
while(true){
clientSocket = serverSocket.accept();
// Create a reader
bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// Get the client message
while((inputLine = bufferedReader.readLine()) != null)
{System.out.println(inputLine);}
serverSocket.close();
System.out.println("close");
}
}
catch(IOException e)
{
System.out.println(e);
}
}
}
And a client would almost be the same:
import java.net.Socket;
import java.io.PrintWriter;
public class client
{
private static Socket socket;
private static PrintWriter printWriter;
public static void main(String[] args)
{
try
{
//change "localhost" to the ip address that the client is on, and this number to the port
socket = new Socket("localhost",63400);
printWriter = new PrintWriter(socket.getOutputStream(),true);
printWriter.println("Hello Socket");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
If I am not mistaken printWriter is a 16-bit operation, and in order to reduce lag, if you were just sending text then you might want to use printStream(). I believe that this might be a bit quicker.