Can't connect client to server between 2 PCs socket in java - java

I have a problem, that when I create 2 files (Client.java and Server.java) on the same PC, it works. But when I send the Client.java file to another PC, it doesn't work. I also turn off fire wall but it still doesn't work.
Class Sever.java:
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
try {
System.out.println("loading..");
ServerSocket serverSocket = new ServerSocket(6667);
Socket socket = serverSocket.accept();
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
String str = dataInputStream.readUTF();
System.out.println(str);
dataInputStream.close();
socket.close();
System.out.println("end");
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
Class Client.java:
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) {
try {
System.out.println("client connecting...");
byte[] addr = {(byte) 192, (byte) 168, (byte) 9, (byte) 9};
InetAddress inetAddress = InetAddress.getByAddress("lvh", addr);
Socket socket = new Socket(inetAddress, 6667);
//socket.setSoTimeout(999999999);
System.out.println(socket.isConnected());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF("hello");
dataOutputStream.flush();
dataOutputStream.close();
socket.close();
System.out.println("end");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I send class Client.java to other PC and get error "Connection timed out" like this picture (T_T):
enter image description here
I don't how to fix :(( help plz!!!

You need to open DataOutputStream in both ends before you open DataInputStream.
UPDATE: added code
Server.java
package src;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
try {
System.out.println("loading..");
ServerSocket serverSocket = new ServerSocket(6667);
try (Socket socket = serverSocket.accept()) {
try (DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream())) {
try (DataInputStream dataInputStream = new DataInputStream(socket.getInputStream())) {
String str = dataInputStream.readUTF();
System.out.println(str);
}
}
}
System.out.println("end");
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
Client.java
package src;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
try {
System.out.println("client connecting...");
byte[] addr = {(byte) 127, (byte) 0, (byte) 0, (byte) 1};
InetAddress inetAddress = InetAddress.getByAddress("localhost", addr);
try (Socket socket = new Socket(inetAddress, 6667)) {
//socket.setSoTimeout(999999999);
System.out.println(socket.isConnected());
try (DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream())) {
try (DataInputStream dataInputStream = new DataInputStream(socket.getInputStream())) {
dataOutputStream.writeUTF("hello");
}
}
}
System.out.println("end");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server Output
loading..
hello
end
Client Output:
client connecting...
true
end
Hope this helps. :)

Related

How to use Input/Output streams correctly? Server/Client/Threads

I am trying to write a program, where Client is sending a string to a Server using output stream. Server would see what string it is, it compares it to a conditional, and then sends it back to the client and displays a message on client's side. I would like to understand how it works, and what is wrong with my code so far. Once I get it I will implement it with JavaFX.
Client
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class MyClient {
static Socket socket;
static int clientNo;
static DataOutputStream toServer;
static DataInputStream fromServer;
public static void main(String[] args) {
try{
socket = new Socket("localhost", 8888);
System.out.println("Client connected to the server");
fromServer = new DataInputStream(socket.getInputStream());
toServer = new DataOutputStream(socket.getOutputStream());
toServer.writeBytes("listAll");
toServer.flush();
System.out.println("Sending string to the ServerSocket");
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
}
Server
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class MyServer {
static final int PORT = 8888;
static ServerSocket serverSocket;
static Socket socket;
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(PORT);
System.out.println("Server started at " + new Date());
System.out.println("Server on PORT: " + PORT + " is open");
System.out.println("Server is ready for multiple clients!");
System.out.println("Waiting for request...");
while(true){
socket = MyServer.serverSocket.accept();
new Thread(new HandleClient(MyClient.socket)).start();
}
} catch (IOException ex) {
System.err.println("Server Error: " + ex.getMessage());
}
}
}
Thread
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class HandleClient implements Runnable {
private Socket socket;
public static int clientNo = 1;
public static int condition;
static DataInputStream input ;
static DataOutputStream output;
static String message;
public HandleClient(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
switch (condition) {
case 1:
break;
case 2:
System.out.println("list all");
break;
case 3:
break;
default:
System.out.println("Client #" + clientNo + " connected!");
clientNo++;
try {
input = new DataInputStream(socket.getInputStream());
output = new DataOutputStream(socket.getOutputStream());
message = input.readUTF();
System.out.println(message);
if("listAll".equals(message)){
HandleClient.condition = 2;
new Thread(new HandleClient(socket)).start();
}
} catch (IOException ex) {
System.err.println("One of the clients disconnected");
}
break;
}
}
}
I really appreciate any help! I understand I might have some code missing to send the response back to the client? Please let me know if the direction I am going is good.

What should the Client class of this EchoServer class be?

I am trying to write the Client class of this EchoServer so that the server can echo my input. It seems that the EchoServer can only read the client's inputs and print it without echoing it again.
Here's the EchoServer class.
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class EchoServer implements Runnable {
Socket socket;
public EchoServer(Socket socket) {
this.socket = socket;
}
public void run() {
System.out.printf("connection received from %s\n", socket);
try {
PrintWriter pw = new PrintWriter(socket.getOutputStream());
Scanner in = new Scanner(socket.getInputStream());
while (in.hasNextLine()) {
String line = in.nextLine();
System.out.printf("%s says: %s\n", socket, line);
pw.printf("echo: %s\n", line);
pw.flush();
}
pw.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(4343);
System.out.printf("socket open, waiting for connections on %s\n",serverSocket);
while (true) {
Socket socket = serverSocket.accept();
EchoServer server = new EchoServer(socket);
new Thread(server).start();
}
}
}
This is my EchoClient class, it reads the system input and writes it to the socket.
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class EchoClient {
Socket socket;
private Scanner in;
private PrintWriter out;
public EchoClient(String address, int port) {
try {
socket = new Socket(address, port);
System.out.println("Connected!");
in = new Scanner(System.in);
out = new PrintWriter(socket.getOutputStream());
} catch (UnknownHostException u) {
System.out.println(u);
} catch (IOException e) {
System.out.println(e);
}
String line = "";
while (!line.equals("over")) {
line = in.nextLine();
out.println(line);
}
out.close();
}
public static void main(String[] args) throws IOException {
EchoClient c1 = new EchoClient("127.0.1.1", 4343);
EchoClient c2 = new EchoClient("127.0.1.1", 4343);
}
}
It seems that the Printwriter of EchoServer is not writing the echo statements. I wonder why?

Error When Sending String Between Client And Server

When I send a String from my client to my server, the server always throws a
java.net.SocketException: Connection reset
If I send a Integer or other types other than a String, the exception would not have been thrown and the program runs absolutely fine.
Client Class:
import java.io.*;
import java.net.*;
public class TestingClient {
public static void main(String[] args) {
try {
Socket clientSocket = new Socket("localhost", 9998);
DataOutputStream outputStream = new DataOutputStream(clientSocket.getOutputStream());
outputStream.flush();
outputStream.writeBytes("hello");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server Class:
import java.io.*;
import java.io.IOException;
import java.net.*;
public class TestingServer {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(9998);
Socket connectionToClient = serverSocket.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(connectionToClient.getInputStream()));
System.out.println(input.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Well, "hello" isn't a byte[]. On the client, write the String with DataOutputStream.writeUTF(String) and then flush(). Something like
outputStream.writeUTF("hello");
outputStream.flush();
and on the server, you can't use a BufferedReader. You need something like DataInputStream.readUTF()
DataInputStream dis = new DataInputStream(
connectionToClient.getInputStream());
System.out.println(dis.readUTF());

Android java : How to send message from server to a specific client any time

I tried to send message from server to client but if i send message the client needs to connect again or println again...
So how does it work?
I tried to println again from server to client but the client wont receive it.
So how to send message to a specific client at any time.
Server:
package server.server.com;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.ArrayList;
public class Server extends Thread {
private static ServerSocket serverSocket;
public static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
static InputStream is;
static OutputStream os;
static byte[] buf;
static BufferedReader reader;
static BufferedWriter writer;
static double ConsoleMessage;
public static String output;
static BufferedReader bufferedReader2;
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(12345);
} catch (IOException e) {
System.out.println("Could not listen on port: 12345");
}
System.out.println("Server started. Listening to the port 12345");
while (true) {
try {
clientSocket = serverSocket.accept();
inputStreamReader = new InputStreamReader(
clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
PrintWriter out = new PrintWriter(
clientSocket.getOutputStream(), true);
InputStream inputStream = new ByteArrayInputStream(
bufferedReader.readLine().getBytes(
Charset.forName("UTF-8")));
bufferedReader2 = new BufferedReader(new InputStreamReader(
inputStream));
output = bufferedReader2.readLine();
System.out.println(output);
out.flush();
out.close();
inputStreamReader.close();
clientSocket.close();
} catch (IOException ex) {
System.out.println("Problem in message reading");
}
}
}
}
Client:
client = new Socket();
client.connect(
new InetSocketAddress(
"IP-ADDRESS",
PORT),
5000);
in = new BufferedReader(
new InputStreamReader(
client.getInputStream()));
printlng = new PrintWriter(
client.getOutputStream());
printlng.println(mLongitude);
printlng.flush();
try {
if ((Response = in
.readLine()) != null) {
....
You should take a look at http://developer.android.com/google/gcm/index.html. Maybe you could take advantage of push notifications in your app.
Maybe you can do something like this
Server:
private boolean sendMessage(final String msg, final String dstIp, final int dstPort) {
DatagramSocket sendSocket = null;
try {
sendSocket = new DatagramSocket();
final InetAddress local = InetAddress.getByName(dstIp);
final int msg_length = msg.length();
final byte[] message1 = msg.getBytes();
final DatagramPacket sendPacket = new DatagramPacket(message1,
msg_length, local, dstPort);
sendSocket.send(sendPacket);
} catch (final Exception e) {
e.printStackTrace();
return false;
} finally {
if (sendSocket != null) {
sendSocket.disconnect();
sendSocket.close();
sendSocket = null;
}
}
return true;
}
Client:
public static void receiveMessage() {
if ((socket == null) || socket.isClosed()) {
socket = new DatagramSocket(BROADCAST_PORT);
socket.setSoTimeout(5000);
}
try {
idMsgs.clear();
while ((socket != null) && !socket.isClosed()) {
socket.setReuseAddress(true);
socket.setSoTimeout(10000);
try {
final byte[] receiveBuffer = new byte[sizepck];
final DatagramPacket packet = new DatagramPacket(
receiveBuffer, receiveBuffer.length);
socket.receive(packet);
} catch (final SocketTimeoutException e) {
} catch (final Throwable e) {
}
}
} catch (final Throwable e1) {
try {
Thread.sleep(TIME_RETRY);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
finally {
if (socket != null) {
socket.close();
}
}
}

Java server / client sending array, Check in check out

Im having a little problem i have managed to send info from client to server etc... but i want to be able to do it though telnet also (Open it up and say go telnet 127.0.0.1 4444, and then put in like 1 2 3 and then it comes up in the server just like it would if sending via the client. At the moment im getting this error:
java.io.StreamCorruptedException: invalid stream header: 310D0A32
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at ConnectionHandler.run(server1.java:73)
at java.lang.Thread.run(Unknown Source)
Let me know if i'm doing anything wrong please:
My main goal for this is to have it so i can enter say Username, ID and Name and then be able to recall them with a time, Like a very simple check in check out system. Would really love some help <3 :)
Client:
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class client1 {
public static void main(String[] args) {
try {
// Create a connection to the server socket on the server application
Socket socket = new Socket("localhost", 7777);
// Send a message to the client application
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
//oos.writeObject("A B C");
String data[]=new String[3];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter details for the array");
for(int x=0;x<3;x++){
System.out.print("Enter word number"+(x+1)+":");
data[x]=br.readLine();
}
oos.writeObject(data);
System.out.println("Details sent to server...");
oos.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.ClassNotFoundException;
import java.lang.Runnable;
import java.lang.Thread;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class server1
{
private ServerSocket server;
private int port = 4444;
public server1()
{
try
{
server = new ServerSocket(port);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
server1 example = new server1();
example.handleConnection();
}
public void handleConnection()
{
System.out.println("Waiting for client message got...");
// The server do a loop here to accept all connection initiated by the
// client application.
while (true)
{
try
{
Socket socket = server.accept();
new ConnectionHandler(socket);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
class ConnectionHandler implements Runnable
{
private Socket socket;
public ConnectionHandler(Socket socket)
{
this.socket = socket;
Thread t = new Thread(this);
t.start();
}
public void run()
{
try
{
// Read a message sent by client application
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
String message[] = (String[]) ois.readObject();
//System.out.println("Message Received from client: " + message);
//b(message);
printArray(message);
ois.close();
socket.close();
System.out.println("Waiting for client message is...");
}
catch (IOException e)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
private void b(String message) {
List<String> list = new ArrayList<String>();
String[] arr = list.toArray(new String[0]);
System.out.println("Array is " + Arrays.toString(arr));
}
private void printArray(String[] arr){
for(String s:arr){
System.out.println(s);
}
}

Categories

Resources