Java Client won't connect to remote server - java

Bare with me as it's been a while since I've been on here and I know there's format rules for questions. I have coded two java applications, both are pretty simple. One being a server and two being a client that connects to the server via socket. Now this works on my computer but when I have a buddy run on his computer it doesn't connect. I want the server to be able to run on my computer and anyone who has the client can connect.
The relevant code for the server:
public static void main(String[] args) throws IOException {
// write your code here
System.out.println("Server Running...");
int port = 1020, backlog = 5;
String ipAddress = "2552:548:41aa:c3f0:563c:hgj9:8ca2:b3aa";
ServerSocket serverSocket = new ServerSocket(port, backlog, InetAddress.getByName(ipAddress));
Server server = new Server(serverSocket);
server.startServer();
}
The relevant code for the client:
public class Client{
public String username;
private Socket socket = new Socket("2552:548:41aa:c3f0:563c:hgj9:8ca2:b3aa", 1020);
public BufferedReader bufferedReader;
public BufferedWriter bufferedWriter;
public ChatController chatController;
public Client(String username) throws IOException {
try {
this.username = username;
this.bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bufferedWriter.write(username);
bufferedWriter.newLine();
bufferedWriter.flush();
listenForMessage();
} catch (IOException e) {
closeEverything(socket, bufferedReader, bufferedWriter);
}
}
Like I said, this works on my computer but the not when client is on a different computer. My thoughts are that the issue is on the client side, possibly not using an open port? Thank you in advance and let me know if I need to edit if it's not a proper question format.

Related

does not read anything using ObjectInputStream in Java socket

I created a simple server and a client, but the server could not read anything that was sent from the client. I also add a print statement after I sent the string, but it cannot be printed either.
public class Server {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ServerSocket serverSocket = new ServerSocket(6666);
Socket clientSocket = serverSocket.accept();
System.out.println("accepting client at address " + clientSocket.getRemoteSocketAddress());
ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream());
String input = (String) in.readObject();
System.out.println(input);
out.writeObject("Received");
out.flush();
}
}
Below is the client, and I just want to send a string "?????does not send":
public class Test {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Client client = new Client();
client.sentInfo();
}
private static class Client {
private ObjectInputStream objectInputStream;
private ObjectOutputStream objectOutputStream;
public Client() throws IOException {
Socket socket = new Socket("127.0.0.1", 6666);
this.objectInputStream = new ObjectInputStream(socket.getInputStream());
this.objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
}
public void sentInfo() throws IOException, ClassNotFoundException {
this.objectOutputStream.writeObject("?????does not send");
this.objectOutputStream.flush();
System.out.println("????????");
Message resp = (Message) this.objectInputStream.readObject();
System.out.println(resp.getMessage());
}
}
}
I tried something else, if I just use InputStream and use a buffer to read bytes, like this:
Server code
This is the client code: client code
The code in the two link above would work. However, it would not work if I tried to use ObjectInputStream:
This is the server: server
This is the client: client
This is the Message object I want to send: Message class
Can someone explain this for me please? Thanks!
To read Strings from a socket use something like this:
DataInputStream input = new DataInputStream(clientSocket.getInputStream());
String message = input.readUTF();
You can open multiple streams from a socket, so if you want to read something else that really needs the ObjectInputStream than it can be open as well. Don't forget to properly close the streams & sockets.

(Java) Getting two threads to communicate with each other whilst running?

I'm learning java. I'm trying to make a simple client/server chat system. What I have so far is a program where the server accepts multiple client connections by giving them each a seperate thread.
My problem now, is that I can't figure out how to get an input from one client, and then have it be sent amongst all of the clients, thus essentially have a very very simple chat mechanic. How would I go about accomplishing this? What would be the simpler way?
My code so far is here;
class Client {
public static void main(String argv[]) throws Exception {
String sentMessage; //variable for input
String receivedMessage; //variable for output
String status;
boolean running;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("127.0.0.1", 5622); //name of computer to connect with and port number to use
DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer =
new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Client Side\n");
running = true;
while(running)
{
sentMessage = inFromUser.readLine(); //user inputs text to variable 'xInput'
outToServer.writeBytes(sentMessage + '\n'); //the variable is sent to the server
status = inFromServer.readLine();
System.out.println("FROM SERVER: " + status); //display to user
}
clientSocket.close();
}
}
The server code.
class Server {
public static void main(String argv[]) throws Exception {
String clientMessage;
boolean listening = true;
int portNumber = 5622;
try (ServerSocket serverSocket = new ServerSocket(portNumber)) {
while (listening) {
new ServerThread(serverSocket.accept()).start();
}
} catch (IOException e) {
System.err.println("Could not listen on port " + portNumber);
System.exit(-1);
}
}
}
The thread that handles the client connections.
public class ServerThread extends Thread {
private Socket socket = null;
public ServerThread(Socket socket) {
super("ServerThread");
this.socket = socket;
}
public void run () {
int msgCnt = 0;
try (
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
) {
//something needs to go here
} catch (IOException e) {
e.printStackTrace();
}
}
If you are looking for a simple client-server communication samples then please have a look at below posts where I have described it step by step.
Multiple clients access the server concurrently
Java Server with Multiclient communication.

Reading and writing from a socket produces no output?

I'm creating an application which will need to transmit data back and forth between multiple computers on a network. Because of the way the data is to be sent, the client computers will be running the socket server, and the coordinating computer will be running the client socket.
I've created simple classes which are simply intended to encapsulate reading from and writing to these sockets. However, instead of reading anything, the receiving socket simply outputs nothing. I have confirmed that both client and server have a connection.
In the following Server and Client classes, the Socket is made public for debugging purposes only.
public class Server {
public Socket client;
private DataInputStream inStr;
private PrintStream outStr;
public Server() throws UnknownHostException, IOException {this("localhost");}
public Server(String hostname) throws UnknownHostException, IOException {
client = new Socket(hostname, 23);
inStr = new DataInputStream(client.getInputStream());
outStr = new PrintStream(client.getOutputStream());
}
public void send(String data) {outStr.print(data); outStr.flush();}
public String recv() throws IOException {return inStr.readUTF();}
}
The following is my Client:
public class Client {
private ServerSocket serv;
public Socket servSock;
private DataInputStream inStr;
private PrintStream outStr;
public Client() throws IOException {
serv = new ServerSocket(23);
servSock = serv.accept();
inStr = new DataInputStream(servSock.getInputStream());
outStr = new PrintStream(servSock.getOutputStream());
}
public void send(String data) {outStr.print(data); outStr.flush();}
public String recv() throws IOException {return inStr.readUTF();}
}
The Client class is instantiated, and the program started. Then, in a separate program, the Server is instantiated and started:
Server s = new Server(); System.out.println(s.client.isConnected());
while(true) {System.out.println(s.recv()); Thread.sleep(200);}
Client c = new Client(); System.out.println(c.servSock.isConnected());
while(true) {c.send("Hello World!"); Thread.sleep(200);}
isConnected() returns true for both the Client and the Server.
What could be causing this? I've never had to use sockets before now.
DataInputStream.readUTF() expects the first two bytes to be the number of bytes to read, but PrintStream.print(String) will convert the string to bytes and write them as-is.
DataOutputStream.writeUTF(String) will write the length like readUTF() expects.

Cant send data from Server to client only viceverse using java

been trying to figure this problem out for about 5 hours but cant seem to see it, although all the steps are done to send data, I can only receive messages to the server, but not from server to client. I'm in the early stages of building/learning how to do a chat client program in command line. The following is the server code:
The CServer class:
public class CServer {
private static int port=2008, maxConnections=0;
private static String shutDownServer = "no";
public static void main(String[] args) throws IOException{
ServerSocket listen = new ServerSocket(port);
Socket server;
while(shutDownServer.equalsIgnoreCase("no")){
doComm connection;
System.out.println("\nWaiting for clients to connect...");
server = listen.accept(); // accept incomming connections from client
System.out.println("Client connected. Location: " + server.getInetAddress().getHostName());
connection = new doComm(server);
Thread thread = new Thread(connection);
thread.start();
}
}
public void shutDownServer(String command){
this.shutDownServer = command;
}
}
Now the doComm class that handles each client in thread:
public class doComm implements Runnable{
Socket server;
private String clientData;
public doComm(Socket server){
this.server = server;
}
public void run(){
try {
BufferedReader fromClient = new BufferedReader(new InputStreamReader(server.getInputStream()));
DataOutputStream toClient = new DataOutputStream(server.getOutputStream());
clientData = fromClient.readLine();
System.out.println("Client sent: "+clientData);
(( The problem -imo- may be either this statement: ))
toClient.writeBytes("Recieved your sentence '"+clientData+"' and more to come :)!");
//server.close();
} catch (IOException e) {
System.out.println("IOException on socket listen: " + e);
e.printStackTrace();
}
}
}
Now the client class CClient:
public class CClient {
static String address = "localhost";
static int port = 4444;
static Socket echoSocket;
public CClient(int port, String addr){
changePort(port);
changeAddr(addr);
}
public static void main(String[] args) throws IOException, UnknownHostException{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the port to connect to: ");
int temp_port = Integer.parseInt(scan.nextLine());
System.out.println("Please enter the address of server: ");
System.out.flush();
String temp_addr = scan.nextLine();
CClient client = new CClient(temp_port,temp_addr);
PrintWriter out = null;
BufferedReader in = null;
try{
System.out.flush();
echoSocket = new Socket(address,port);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
}
catch(IOException e){
System.err.println("IOException error: " + e.getStackTrace());
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("thingy prints right after this...");
(( or here: ))
System.out.println("echo: " + in.readLine());
}
}
public void changePort(int port){
this.port=port;
}
public void changeAddr(String addr){
this.address=addr;
}
}
clientData = fromClient.readLine();
toClient.writeBytes("Recieved your sentence '"+clientData+"' and more to come :)!");
This is a very common problem whose root cause is the failure to document and specify the protocol being used for communication. Here you are receiving lines but sending bytes. If you had a protocol document, it would either specify that lines were exchanged or that arbitrary units of bytes were exchanged. That would show that one of these lines of code is wrong, and you could fix it. But without a protocol specification, you can't even tell which side is wrong.
Please, take my advice from years of painful lessons -- document a protocol before you implement. Then, if it doesn't work, you can follow this three step process:
Does the client follow the documented protocol? If not, it is broken.
Does the server follow the documented protocol? If not, it is broken.
The protocol specification is broken.
In this case, the protocol specification would document what constitutes a "message" for your protocol. It would then be each side's responsibility to send complete messages and find these message boundaries on receive. However, in your case, one piece of code expects a line terminator to mark a message boundary and the other side doesn't send one.
Is the sender wrong to omit a message boundary? Is the receiver wrong to insist on receiving one? Nobody knows because there's no specification to say what's the right thing to do.

Handle streams with multiple clients?

basically what i want to do is develop a chat program(something between an instant messenger and IRC) to improve my java skills.
But I ran into 1 big problem so far: I have no idea how to set up streams properly if there is more than one client. 1:1 chat between the client and the server works easily, but I just don't know what todo so more than 1 client can be with the server in the same chat.
This is what I got, but I doubt its going to be very helpful, since it is just 1 permanent stream to and from the server.
private void connect() throws IOException {
showMessage("Trying to connect \n");
connection = new Socket(InetAddress.getByName(serverIP),27499);
showMessage("connected to "+connection.getInetAddress().getHostName());
}
private void streams() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\n streams working");
}
To read from multiple streams in one program, you're going to have to use multithreading. Because reading from streams is synchronous, you'll need to read from one stream for each thread. See the java tutorial on threads for more info on multithreading.
I've done this several times with ServerSocket(int port) and Socket ServerSocket.accept(). This can be pretty simple by having it listen to the one port you want your chat server client listening on. The main thread will block waiting for the next client to connect, then return the Socket object to that specific client. Usually you'll want to put them in a list to generically handle n-number of clients.
And, yes, you will probably want to make sure each Socket is in a different thread, but that's entirely up to you as the programmer.
Remember, there is no need to re-direct to another port on the server, by virtue of the client using a different source port, the unique 5-tuple (SrcIP, SrcPort, DstIP, DstPort, TCP/UDP/other IP protocol) will allow the one server port to be re-used. Hence why we all use stackoverflow.com port 80.
Happy Coding.
Made something like that a few months back. basically I used a separate ServerSocket and Thread per client server side. When client connects you register that port's input and output streams to a fixed pool and block until input is sent. then you copy the input to each of the other clients and send. here is a basic program run from command line:
Server code:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class ChatServer {
static int PORT_NUMBER = 2012;
public static void main(String[] args) throws IOException {
while (true) {
try (ServerSocket ss = new ServerSocket(PORT_NUMBER)) {
System.out.println("Server waiting #" + ss.getInetAddress());
Socket s = ss.accept();
System.out.println("connection from:" + s.getInetAddress());
new Worker(s).start();
}
}
}
static class Worker extends Thread {
final static ArrayList<PrintStream> os = new ArrayList(10);
Socket clientSocket;
BufferedReader fromClient;
public Worker(Socket clientSocket) throws IOException {
this.clientSocket = clientSocket;
PrintStream toClient=new PrintStream(new BufferedOutputStream(this.clientSocket.getOutputStream()));
toClient.println("connected to server");
os.add(toClient);
fromClient = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
}
#Override
public void run() {
while (true) {
try {
String message = fromClient.readLine();
synchronized (os) {
for (PrintStream toClient : os) {
toClient.println(message);
toClient.flush();
}
}
} catch (IOException ex) {
//user discnnected
try {
clientSocket.close();
} catch (IOException ex1) {
}
}
}
}
}
}
Client code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
final BufferedReader fromUser = new BufferedReader(new InputStreamReader(System.in));
PrintStream toUser = System.out;
BufferedReader fromServer;
final PrintStream toServer;
Socket s = null;
System.out.println("Server IP Address?");
String host;
String port = "";
host = fromUser.readLine();
System.out.println("Server Port Number?");
port = fromUser.readLine();
s = new Socket(host, Integer.valueOf(port));
int read;
char[] buffer = new char[1024];
fromServer = new BufferedReader(new InputStreamReader(s.getInputStream()));
toServer = new PrintStream(s.getOutputStream());
new Thread() {
#Override
public void run() {
while (true) {
try {
toServer.println(">>>" + fromUser.readLine());
toServer.flush();
} catch (IOException ex) {
System.err.println(ex);
}
}
}
}.start();
while (true) {
while ((read = fromServer.read(buffer)) != -1) {
toUser.print(String.valueOf(buffer, 0, read));
}
toUser.flush();
}
}
}

Categories