Connecting two machines using Socket - java

I tried to connect two machines using Socket.
I put client code in Machine A:
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try {
Socket s = new Socket("IP ADDRESS",5555);
// Socket s = new Socket("localhost",6669);
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
} catch(Exception e) {
System.out.println(e);
}
}
}
Run the server code in Machine B
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(5555);
Socket s = ss.accept(); //establishes connection
DataInputStream dis = new DataInputStream(s.getInputStream());
String str = (String) dis.readUTF();
System.out.println("message= " + str);
ss.close();
} catch(Exception e) {
System.out.println(e);
}
}
}
Both in machine in same network
But its not running and no error also coming in CMD.

First of all, when I compile the code using "localhost" as the hostname, and run the client and server apps on the same machine ... it works. The server receives the message and prints it.
From this, I conclude that the code is correct (enough) and the real problem is something to do with your networking; e.g.
It might be a routing problem.
It might be a firewall problem.
There might be something wrong with your physical network or network interfaces.
However none of these are programming problems.

Related

Java Beginner - Issue with Socket Connection refused

I am complete beginner and i have assignment to send something to server and get it back while using threads too.
My problem is that no matter which port I use, I get connection refused.
I think it might something to do with threads, but I am unsure what to do with them as it seems both start properly and client is the one throwing exception. I read somewhere that server should have some time to start connection so I put sleep but same thing again.
Main:
package advancedjavaassignment1;
public class MAIN {
public static void main(String[] args) {
SERVER.mainServer();
CLIENT.mainClient();
}
}
SERVER:
package advancedjavaassignment1;
import java.net.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
public class SERVER {
static void mainServer() {
serverTHREAD serverThread = new serverTHREAD();
serverThread.start();
try (
ServerSocket calcServer = new ServerSocket(10001); //Server created on port 2390
Socket inSocket = calcServer.accept(); //Server is listening
DataInputStream FromClient = new DataInputStream(inSocket.getInputStream());
DataOutputStream ToClient = new DataOutputStream(inSocket.getOutputStream());) {
int a = FromClient.readInt();
ToClient.writeInt(a);
}
catch (IOException e) {
System.out.println(e.getMessage()+ "Server");
}
}
}
}
CLIENT:
package advancedjavaassignment1;
import java.net.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
public class CLIENT {
static void mainClient() {
serverTHREAD clientThread = new serverTHREAD();
clientThread.start();
try {Thread.sleep(2000); System.out.println("break");} catch (InterruptedException ex) { }
try (Socket ClientSocket = new Socket("localhost",80);
DataInputStream FromServer = new DataInputStream(ClientSocket.getInputStream());
DataOutputStream ToServer = new DataOutputStream(ClientSocket.getOutputStream());) {
ToServer.writeInt(10);
int sum = FromServer.readInt();
System.out.println(sum);
ClientSocket.close();
}
catch(IOException exception)
{
System.out.println(exception.getMessage() + " - Client");
}
}
}
Looks like your server runs on port 10001 (although you wrote 2390 in the comment) and the client tries to connect to port 80. The client finds no server listening on that port, hence the connection refused error.
My apology, I forgot to change it, as I was experimenting with everything, this does not work even when ports are same.
I solved this by implementing Runnable. Worked immediately.

Socket Communication Between Separate Machines

Take the following basic programs:
import java.io.*;
import java.net.*;
public class TestServer {
public static void main(String[] args) throws IOException {
ServerSocket listener = new ServerSocket(12345);
try {
while (true) {
Socket socket = listener.accept();
try {
PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
out.println(new java.util.Date().toString());
out.close();
} finally {
socket.close();
}
}
} finally {
listener.close();
}
}
}
public class TestClient {
public static void main(String[] args) {
try {
Socket socket = new Socket("0.0.0.0",12345); // Stack trace points to this line as the one with the error
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println(in.readLine());
in.close();
socket.close();
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
}
}
}
The TestServer program waits for a client to connect to it so that it can send information, which is, in this case, the current date, to the client. At my home computer in my IDE (JCreator, by the way), I can run both the TestServer program and the TestClient program on the same computer and get the desired result. The problem is that when I run the TestClient program on a different computer and attempt to connect to the TestServer program, I keep getting the message IOException: Connection refused.
Is there any way to get this to work?
You're trying to connect to the server with a wrong IP address (0.0.0.0).
You'll need to know the IP address of the computer running the server program and use that to instantiate the socket in your client program.
Note that the server should be reachable from the client computer.

Two-way Java chat using socket

I tried to find something similar to help me with my code and I also tried to do it by myself but I got stuck on the end and I would really appreciate if someone would help me with that.
So I have already working simple Java Client/Server code and what i want to do is to upgrade it so it can work both ways, right now after launching the server and connecting to it by the client everything what u write as a client will be shown on the server too and i want to upgrade it so what i write on the client will be shown on the server and what i write on the server will be shown on the client.
myServer.java
import java.io.*;
import java.net.*;
public class myServer {
public static void main (String[] args) {
try {
int i=0;
ServerSocket ss = new ServerSocket(9000);
System.out.println("Listening...");
Socket s = ss.accept();
System.out.println("Connection accepted");
InputStream d1 = s.getInputStream();
while ((char)i !='q')
{
i = d1.read();
System.out.print((char)i);
}
s.close();
ss.close();
} catch (Exception e) {System.out.println("Error"); }
}
}
myClient.java
import java.io.*;
import java.net.*;
public class myClient {
public static void main(String[] args) {
try {
int i=0;
Socket s=new Socket("localhost",9000);
OutputStream o = s.getOutputStream();
while ((char)i !='q')
{
i = System.in.read();
o.write((char)i);
}
s.close();
} catch(Exception e) {System.out.println("Error"); }
}
}
Thank You in advance.

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();
}
}

Java Socket Constructor, Socket(String hostName, int port), Hangs

I'm trying to make a simple client/server program. I have opened a ServerSocket, but can't seem to connect to it with the client socket I've created.
I've been looking for an answer for a while now - frankly, I'm not exactly sure what to even search for with this problem.
Here's the client code:
import java.io.*;
import java.net.*;
public class Client{
public static void main(String[] args) throws IOException {
Socket s = null;
try{
System.out.println("connecting to host...");
s = new Socket("dagobah", 6464);
}catch (UnknownHostException e) {
System.err.println("Can't connect");
System.exit(1);
}
System.out.println("Connected to host");
s.close();
}
}
Here's the server code:
import java.net.*;
import java.io.*;
import java.util.*;
public class server{
public static void main(String[] args) throws IOException{
ServerSocket serverSocket = null;
try{
serverSocket = new ServerSocket(6464);
}catch (IOException e){
System.err.println("fail to start server");
System.exit(1);
}
System.out.println("Server started : )");
Socket clientSocket = null;
try{
System.out.println("waiting for a client...");
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.out.println("fail can't accept client connection");
System.exit(-1);
}
System.out.println("client connected");
clientSocket.close();
serverSocket.close();
}
}
The client never makes it past the try block
client output: connecting to host...
server output: Server started : )
waiting for a client...
Since posting this question, I have learned that this is a problem specific to my computer. I'm running Linux 2.6.38-11-generic x86_64 GNU/Linux Ubuntu Natty
Any and all help will be much appreciated! : )
The Socket constructor does not actually connect, but it does try to resolve the host name into an IP address. It looks like in this case the name resolution is taking a long time, and would eventually time out, throwing an UnknownHostException. I've heard this can take minutes on Windows.
How is dagobah resolved, by DNS or? Try using the IP address instead of the name.
You have a problem with the Socket constructor. Check how you are trying to resolve dagobah to an IP address. Try your code with localhost or 127.0.0.1.
I tried and it works perfectly fine.
Try to replace your line
s = new Socket("dagobah", 6464);
with
s = new Socket("127.0.0.1", 6464);
That might can solve your query. Seems like your dagobah is really not your HostName as indicated by you. Do recheck that, by Right Clicking your My Computer and go to Properties, and find the name under Computer Name. The above line will solve the issue for you.

Categories

Resources