Connecting two computers for client server communication in java - java

This code is about client and server communication in java. I can run both codes in my PC and can connect client and server. But how will I connect 2 computers as a client and server. Here are my codes for server and client as follows:
MyServer1
//code for server
import java.io.*;
import java.net.*;
public class MyServer1
{
ServerSocket ss;
Socket s;
DataInputStream dis;
DataOutputStream dos;
public MyServer1()
{
try
{
System.out.println("Server Started");
ss=new ServerSocket(10);
s=ss.accept();
System.out.println(s);
System.out.println("CLIENT CONNECTED");
dis= new DataInputStream(s.getInputStream());
dos= new DataOutputStream(s.getOutputStream());
ServerChat();
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main (String as[])
{
new MyServer1();
}
public void ServerChat() throws IOException
{
String str, s1;
do
{
str=dis.readUTF();
System.out.println("Client Message:"+str);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
s1=br.readLine();
dos.writeUTF(s1);
dos.flush();
}
while(!s1.equals("bye"));
}
}
MyClient1
//code for client
import java.io.*;
import java.net.*;
public class MyClient1
{
Socket s;
DataInputStream din;
DataOutputStream dout;
public MyClient1()
{
try
{
//s=new Socket("10.10.0.3,10");
s=new Socket("localhost",10);
System.out.println(s);
din= new DataInputStream(s.getInputStream());
dout= new DataOutputStream(s.getOutputStream());
ClientChat();
}
catch(Exception e)
{
System.out.println(e);
}
}
public void ClientChat() throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
String s1;
do
{
s1=br.readLine();
dout.writeUTF(s1);
dout.flush();
System.out.println("Server Message:"+din.readUTF());
}
while(!s1.equals("stop"));
}
public static void main(String as[])
{
new MyClient1();
}
}

Client Just needs the IP of the Server.You have to find out the IP of the server and tell the client about it, like:
String serverName = "IP of server comes here"; // Indicating the place to put Server's IP
s = new Socket(serverName, 10);
Server needs no change.

You have to just enter ip of the server while creating Socket Instance.
i suggest you to follow steps
1) start hotspot in any one computer which you going to use as server
2) in second computer start wifi and connect with hotspot which we just started.
3) now ho to sharing center and click on network you connect and check detail and copy dns server ip and paste it in client program

Related

Socket connection program(TCP/IP) working for localhost/common network but not for other IP

I am trying to make connection between a machine(Server) connected to a network(e.g. via hotspot of Network X) and another(Client) connected to hotspot of Network Y.
Issue 1:
The piece of code is working fine if Server and client(can be
multiple) are connected to same Network(say X) but if Server and
client are on different Network(X and Y) then I am getting connection
timeout error.
Issue 2:
If server and client are on same Network(here via router) then also
they are unable to connect with the same above error. I have done port
forwarding(here : 5555) with my router and Firewall and defender put
to Off of both client and server.
What am I missing.Please review !!
Attaching code snippet for Server :
import java.net.*;
import java.io.*;
class ServerSideConnection{
public static void main(String args[]){
try{
while(true){
ServerSocket socket = new ServerSocket(5555);
Socket serverinput = socket.accept();
Mutithrd_excutn mutithrd_excutn_obj = new Mutithrd_excutn(serverinput);
mutithrd_excutn_obj.start();
socket.close();
}
}catch(IOException e){
}
}
}
import java.net.*;
import java.io.*;
class Mutithrd_excutn extends Thread{
public Socket serverinput;
public Mutithrd_excutn(Socket serverinput){
this.serverinput = serverinput;
}
public void run(){
try{
BufferedReader br = new BufferedReader(new InputStreamReader(serverinput.getInputStream()));
PrintWriter pw = new PrintWriter(serverinput.getOutputStream());
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
String str_client = "";
String str_server = "";
while(true){
str_client = br.readLine();
System.out.println("Client : " + str_client);
if(str_client.equals("stop")){
return;
}
str_server = br1.readLine();
pw.println(str_server);
pw.flush();
}
//serverinput.close();
//socket.close();
}catch(IOException e){
}
}
}
Attaching code snippet for Client (here in localhost I am entering
the IP address of Server machine):
import java.io.*;
import java.net.*;
public class ClientSideConnection {
public static void main(String[] args) {
try {
Socket s = new Socket("localhost",5555);
PrintWriter pw = new PrintWriter(s.getOutputStream());
BufferedReader br_client_input = new BufferedReader(new InputStreamReader(System.in));
BufferedReader br_server_output = new BufferedReader(new InputStreamReader(s.getInputStream()));
String str_client = "";
String str_server = "";
while(!str_client.equals("stop")) {
str_client = br_client_input.readLine();
pw.println(str_client);
pw.flush();
if(!str_client.equals("stop")) {
str_server = br_server_output.readLine();
System.out.println("Server : " + str_server);
}
}
br_client_input.close();
br_server_output.close();
s.close();
}catch(IOException e) {
}
}
}
Also,please do write in comment if any point I may have missed n elaborating the problem.
If it is working in the same network but not between different networks then I see the following options:
there is some firewall blocking the connection
or the port forwarding you've setup is done wrong
or you are using the wrong target IP, i.e. the private IP in the target network instead of the public visible IP from the port forwarding
Unfortunately your question does not contain enough details to limit the options further, i.e. it is unknown how the port forwarding is exactly done and which IP address (internal or external) you use as server address in your tests.

Socket won't accept the strings

This is my code:
public class EchoServer {
ServerSocket ss;
Socket s;
DataInputStream din;
DataOutputStream dout;
public EchoServer()
{
try
{
System.out.println("server started");
//ss = new ServerSocket(0);
//System.out.println("listening on port: " + ss.getLocalPort());
ss = new ServerSocket(49731);
s = ss.accept();
System.out.println(s);
System.out.println("connected");
din = new DataInputStream(s.getInputStream());
dout = new DataOutputStream(s.getOutputStream());
Server_chat();
ss.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String[] args) {
new EchoServer();
}
public void Server_chat() throws IOException {
String str;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in ));
do
{
System.out.println("enter a string");
str = br.readLine();
System.out.println("str " + din.readUTF());
dout.flush();
}
while(!str.equals("stop"));
}
}
I verified 49731 port by passing port no. 0 earlier and got this port.
When I run the above code on Netbeans the output shows "server started" and then it keeps on running even though it should show connected and rest of the input I provide.
And then it keeps on running even though it should show connected and
rest of the input I provide.
Why it should go on printing 'connected'?
s=ss.accept();
In this line you are: listens for a connection to be made to this socket and accepts it. The
method blocks until a connection is made.
accept method will wait for a client that connect to him. So you need to provide a client that connect to the server. Otherwise he'll wait forever!
For some examples about how to use socket in java see here and here.
For more about accept() read here

Android TCP server recieves all data on application exit

I'm having the following TCP client code:
public static void register(InetAddress ip, int port, String name) {
try {
Socket clientSocket = new Socket(ip, port);
send("reg:" + name);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void send(String str) {
try {
String sentence = str;
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes(sentence);
} catch (IOException e) {
Log.e("CONNECT", e.getMessage());
}
}
They both are called in onClicks and i know that for sure.
I also have the following Server code:
public static void main(String argv[]) throws Exception {
String clientSentence;
ServerSocket welcomeSocket = new ServerSocket(9876);
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(
connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
outToClient.writeBytes("msg: Hello! kalin pedro");
}
}
When trying to send data to the server i don't get an exception, i also know that I'm connected to it because the application is crashing when i terminate the server application. The problem is that the server doesn't receive anything until i terminate the client application. Everything that i have tried to send until that moment is all received from the server at once. I looked at the network activity tab provided by Android Studio and there is a change when sending data, the server just doesn't receive it(or at least i don't see it receive it) until i terminate the client application.

Java Client Server Chat Program

Guys am sick of this client and server chat program plz help me
my program is compiled and runing but the problem is that when i trying to pass the msg to the server its not working it pass by itself..now what correction i do...
Server Code:
import java.io.*;
import java.net.*;
class serv
{
ServerSocket s;
Socket c;
DataInputStream dis;
DataOutputStream dos;
BufferedReader disi;
public serv()
{
try
{
s = new ServerSocket(2000,0,InetAddress.getLocalHost());
System.out.println("Server is Created");
c = s.accept();
System.out.println("Request Accepted");
}
catch(Exception e)
{
System.out.println(e);
}
}
public void talk()throws IOException,UnknownHostException
{
dis = new DataInputStream(c.getInputStream());
dos = new DataOutputStream(c.getOutputStream());
disi = new BufferedReader(new InputStreamReader(System.in));
while(true)
{
String str = new String(disi.readLine());
dos.writeUTF(str);
System.out.println(str);
}
}
public static void main(String args[])
{
try
{
serv c = new serv();
c.talk();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Client Code:
import java.io.*;
import java.net.*;
class clien
{
Socket c;
DataInputStream dis;
BufferedReader disi;
DataOutputStream dos;
public clien()throws IOException,UnknownHostException
{
c=new Socket(InetAddress.getLocalHost(),2000);
System.out.println("Request is sended");
}
public void talk()throws IOException,UnknownHostException
{
try
{
dis=new DataInputStream(c.getInputStream());
dos=new DataOutputStream(c.getOutputStream());
disi=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
String str=new String(disi.readLine());
dos.writeUTF(str);
System.out.println(str);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String args[])
{
try
{
clien c=new clien();
c.talk();
}
catch(Exception e){ }
}
}
There are tons of problems.
It seems as if you're trying to do some kind of protocol like this:
Client connects to server
Client sends message to server
Server receives message
A peer-to-peer type system. Not sure if you're expecting the server to be seen as another client (you type messages into it to send it to the client), but the problem is that right when the connection establishes, both Client and Server go into a loop. In this loop, there's only 1 thing you can focus on.
Client:
main(String[]) -> connect -> read input from user (loop)
start program -> connect -> start listening for info from server
Server:
main(String[]) -> accept connection -> read input from user (loop)
If you want your client to receive info from the server and be able to send info aswell, you need 2 threads.
static Socket s;
static DataOutputStream out;
static DataInputStream in;
public static void main(String[] args) {
try {
s = new Socket("host", 2000);
out = new DataOutputStream(s.getOutputStream());
in = new DataInputStream(s.getInputStream());
new Thread(new Runnable() {
public void run() {
Scanner scanner = new Scanner(System.in);
String input;
while(!(input = scanner.nextLine()).equals("EXITPROGRAM")) {
out.writeUTF(input); //sends to client
}
}
}).start();
while(true) {
String infoFromServer = in.readUTF();
//you can print to console if you want
}
}catch(Exception e) { }
}
Now, this will allow the client to receive input from the user (from the console) AND receive data from the server aswell. You can use the same structure for your server aswell if that's what you're going for.

TCP socket connection

I'm new to the network communication and I'm trying to build client-server application.
protected void init(){
Server myServer = new Server();
Client myClient = new Client();
}
That's my Client class:
public class Client {
public Client() {
init();
}
private void init() {
Socket echoSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
DataInputStream stdIn = new DataInputStream(System.in);
try {
echoSocket = new Socket("localhost", 1234);
os = new DataOutputStream(echoSocket.getOutputStream());
is = new DataInputStream(echoSocket.getInputStream());
os.writeInt(stdIn.readInt());
echoSocket.getOutputStream().close();
echoSocket.getInputStream().close();
echoSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And that's server:
public class Server {
public Server() {
init();
}
private void init() {
try {
boolean run = true;
ServerSocket ss = new ServerSocket(1234);
Socket s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println(dis.readInt());
s.getInputStream().close();
s.getOutputStream().close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
First of all:
Can I initialize client and server simply like i did? new Server() and new Client()?
Question 2:
Is it important what i initialize at first? client or server?
Question 3:
When i compile this code with client first initialized, i become Connection refused: connect. I know it means that there is no listening socket running on the port you are trying to connect to. That's why server must go first, i think. Is it so? can i fix it using setSoTimeout and how?
Question 4:
When i compile it with server and then client, output is nothing. And i think it has nothing to do with client, because if i try to print "1", for example, it doesn't work either. I think it just waits for the client and does nothing that goes after. How can i fix this? maybe setSoTimeout goes here too?
You can't have both client and server in the same thread.
As you already have observed, the server accepts the connection and tries to read something. It doesn't know that the client is running in the very same thread.
Either make a multi-threaded application, where client and server have their own thread. Or make two prgrams that run independently of each other. The latter would be also the "normal case".
Make two different projects, first run server than client.
Server will write on console "Server started" than run client it will ask your name, type your name press ok . Your name will be sent to server and server will reply saying hello to you.
Here is server code
import java.net.*;
import java.io.*;
import javax.swing.*;
public class Server {
public static void main(String[] args) {
try{
ServerSocket ss= new ServerSocket(2224);
System.out.println("Serever started");
while(true)
{
Socket s=ss.accept();
InputStream is=s.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
OutputStream os=s.getOutputStream();
PrintWriter pw=new PrintWriter(os);
String name=br.readLine();
String message="Hello "+name+"from server";
pw.println(message);
pw.flush();
}
}
catch(Exception exp)
{
System.out.println("Excepttion occured");
}
}
}
Here is client code
import java.net.*;
import java.io.*;
import java.util.Scanner;
import javax.swing.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket s=new Socket("localhost",2224);
InputStream is=s.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
OutputStream os=s.getOutputStream();
PrintWriter pw=new PrintWriter(os,true);
String message = JOptionPane.showInputDialog("Give your name");
pw.println(message);
pw.flush();
String servermessage = br.readLine();
JOptionPane.showMessageDialog(null, servermessage);
s.close();
}
}

Categories

Resources