I have a server/client application written in java. Basically when the client tries to connect to the server locally (127.0.0.1 as IP) everything works fine. However when I use my personal IP address (home address) I get a connection timeout error.
*I have portforwarded correctly, tested using port check tool
*I also checked using netstat -a in command prompt
*I am hosting on port 9005
here is some of my client code, where I assume I am doing somthing wrong:
public void run() throws UnknownHostException, IOException{
String serverAddress = "xx.xx.xx.xxx"; //My actual IP is here in the program
Socket socket = new Socket(serverAddress, 9005);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
String playerName = JOptionPane.showInputDialog(
this,
"Choose Username:",
"Name Selection",
JOptionPane.PLAIN_MESSAGE);
out.println("NEW "+playerName);
I'm fairly new to server programing in Java, any suggestions would be appreciated.
I can post more code if requested, just didn't want to post a mountain of it.
thanks.
EDIT: here is some server code:
private final static int PORT = 9005;
public static void main(String[] args) throws Exception {
Server s = new Server();
s.setSize(50,100);
s.setDefaultCloseOperation(s.EXIT_ON_CLOSE);
s.setVisible(true);
System.out.println("Server running");
ServerSocket listener = new ServerSocket(PORT);
try {
while (true) {
new Handler(listener.accept()).start();
}
Related
I'm trying to make a chat program where the client and the server can chat with each other on different networks (not localhost) I'm currently faced with a problem that i don't know how to solve.
For some reason, the client and the server can't connect to each other, when i write a message to the server with the client, nothing pops up on the server. The tests were run on two different computers, on different networks (Mobile data and Ethernet)
I've used the public ip from my ethernet in the code, and portforwarded it with the matching port number in the code. The server is running on the portforwarded network.
This is my code:
CLIENT:
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class ChatClient {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
DatagramSocket client = new DatagramSocket(7000);
byte[] receivedData = new byte[1024];
byte[] sentData;
InetAddress address = InetAddress.getByName(" PUBLIC IP IS HERE, won't show it for obvious reasons ");
while (true) {
String message = scanner.nextLine();
sentData = message.getBytes();
DatagramPacket dp1 = new DatagramPacket(sentData, sentData.length, address, 7000);
client.send(dp1);
DatagramPacket dp4 = new DatagramPacket(receivedData, receivedData.length);
client.receive(dp4);
String receivedMessage = new String(dp4.getData());
System.out.println(receivedMessage);
}
}
}
SERVER:
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class ChatServer {
public static void main(String[] args) throws IOException {
DatagramSocket server = new DatagramSocket();
Scanner scanner = new Scanner(System.in);
byte[] receivedData = new byte[1024];
byte[] sentData;
while (true) {
DatagramPacket dp2 = new DatagramPacket(receivedData, receivedData.length);
server.receive(dp2);
String storedData = new String(dp2.getData());
System.out.println(storedData);
InetAddress getIP = dp2.getAddress();
int port = dp2.getPort();
String sentMessage = scanner.nextLine();
sentData = sentMessage.getBytes();
DatagramPacket dp3 = new DatagramPacket(sentData, sentData.length, getIP, port);
server.send(dp3);
}
}
}
The code worked when altered to localhost only.
Does anyone know what i'm doing wrong? Any replies are greatly appreciated.
Assuming the client connects to the server, the server needs to specify the port to listen and the client needs to specify IP and port of the server.
Client:
InetAddress address = InetAddress.getByName(" PUBLIC IP IS HERE");
DatagramSocket client = new DatagramSocket();
//...
DatagramPacket dp1 = new DatagramPacket(sentData, sentData.length, address, 7000);//the port should be the publicly exposed port
client.send(dp1);
This connects to the server with specified IP and port.
Server:
DatagramSocket server = new DatagramSocket(7000);//port to forward
This means that the server listens on port 7000 so it is available under that port.
Aside from that, make sure the port forwarding works correctly. If you use UDP, you also need to configure it for TCP.
Also note that UDP does neither confirm nor validate packages. If you want to have those features, you will need to either use TCP or implement those features by yourself.
I am Running into a java.net.BindException: Address already in use (Bind failed) on a server-client socket app
I am trying to learn about Java sockets using a Youtube tutorial as a reference. My code seems to match everything in the video (except variables names) but, when trying to run the server and then the client sockets, I get:
Exception in thread "main" java.net.BindException: Address already in use (Bind failed)
I have tried even printing out the local port just to make sure I connect to the right available port but, nothing works. Is there any documentation I can look into to solve this problem? or any guidance?
Server.java
public class serverSocket {
public static void main(String args[]) throws IOException{
String message, serverResponse;
ServerSocket serverSocket = new ServerSocket(56789);
System.out.print(serverSocket.getLocalPort());
Socket acceptClientRequestSocket = serverSocket.accept();
Scanner serverScanner = new Scanner(acceptClientRequestSocket.getInputStream());
message = serverScanner.next();
System.out.println(message);
serverResponse = message.toUpperCase();
PrintStream newMessage = new PrintStream(acceptClientRequestSocket.getOutputStream());
newMessage.println(serverResponse);
}
}
Client.java
public class clientSocket {
public static void main(String args[]) throws UnknownHostException, IOException {
String message,outputMessage;
Scanner clientInput = new Scanner(System.in);
Socket clientSocket = new Socket("localhost",56789);
Scanner incomingStream = new Scanner(clientSocket.getInputStream());
System.out.println("Enter a message");
message = clientInput.next();
PrintStream printClientStream= new PrintStream(clientSocket.getOutputStream());
printClientStream.println(message);
outputMessage = incomingStream.next();
System.out.println(outputMessage);
}
}
Is there any documentation I can look into to solve this problem? or any guidance?
You have probably your previously exectued program still running. Check the running java processes. Kill the the previous one and try again.
If this wouldn't help try restarting your machine. If the problem persists after that then some service is already running on this port and is starting with the OS. In that case you can either change the port number in your app or disable that service.
I have a problem that's driving me crazy.
Let's say I have client and server (TCP connection):
public class ServerTCP {
public static void main(String args[]) throws IOException {
ServerSocket srvr = new ServerSocket(4380);
Socket skt = srvr.accept();
System.out.print("Client has connected!\n");
skt.close();
srvr.close();
}
}
public class ClientTCP {
public static void main(String args[]) throws IOException {
Socket skt = new Socket("myIPaddress", 4380);
}
}
If I replace IP address from ClientTCP with "localhost", everything works fine. When I start ServerTCP, go to http://www.yougetsignal.com/tools/open-ports/, enter 4380 and hit Check, I got message from terminal "Client has connected!". So that should mean that port forwarding is right and I can receive connections. But, when I try to connect from ClientTCP I cannot do it. No matter what I do (disabled ufw, tried different ports), it's just stuck and I eventually I get connection timeout.
I also tried same thing with Netty, same problem occurs. I am using XUbuntu
16.04 LTS, if that helps. I have no idea what else should I do.
I am making a messaging application that would connect two or more users on a local network and start messaging.It doesnot require an internet connection.
Now I don't know Where to make the socket and where serverSocket?
Who would be the client and who would be the server?
At the time the code that I've written is like this
....
static ServerSocket server;
static Socket client;
public static void main(String[] args) throws IOException {
try{
server=new ServerSocket(65474);
}
catch(IOException e){
System.out.println("Port not Free");
}
while(server.isClose()==false){
client=server.accept();
}
BufferedReader rdr=new BufferedReader(new InputStreamReader(client.getInputStream()));
From here ahead I will get the input from the client.
Is this code correct?Would client connect to the server correctly?
You are infinitely accepting clients BUT you will never get to read their data.
You should put it like that:
while(!server.isClosed() {
client=server.accept();
BufferedReader rdr=new BufferedReader(new InputStreamReader(client.getInputStream()));
}
You can remove the ==false and just negate the boolean youre getting.
It will be set to true if it returns false and false if it returns true.
Dont forget to read the data and to display it on the screen like:
String receivedText = rdr.readLine();
System.out.println(receivedText);
I have searched everywhere to find an answer for this question:
I have a TCP client on my android application that sends an message to the server which is written in Visual Basic .NET Framework 4.
Now i want to send an message from my server to the phone over 3g, it works on wifi and 3g..
private class startserver extends Thread
{
public void server() throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(8765);
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(clientSentence.substring(1));
msgshower = clientSentence.substring(1);
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, "Received: " + msgshower , Toast.LENGTH_LONG).show();
}
});
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
}
#Override
public void run() {
try {
server();
} catch (Exception e) {
e.printStackTrace();
}
}
I start it in the OnCreate method
Now i send a message with (VB.NET)
Private Sub sends(ByVal message As String)
Dim tcp As New TcpClient
tcp.Connect(connectedIP, 8765)
Dim bw As New IO.BinaryWriter(tcp.GetStream)
bw.Write(message)
bw.Close()
tcp.Close()
End Sub
On wifi it will arrive, on 3g it wont... any idea's how to do this?
How do other applications archive this?
I think you're having problem with the ip address asigned by your mobile phone operator. The fact that works on wifi, but not on 3G, I think that is because your mobile(when connected through 3G) doesn't have a public IP address.
When you use SocketServer in your mobile, you're opening a port a waiting for others to connect to it. If your IP address is not reachable from internet, it won't happen (it's like having a computer behind a firewall.)
Could you try to implement the server in the VB machine, assuming that it has a public reachable address? This way, the phone wouldn't act as a server, it wouldn't be necessary to have a reachable address, as long as the VB machine has one. Then, you should use Socket class to bind to the server ip and port.
Totally confused by your code list above..
If you want to host a server in VB.NET, you should not use TcpClient class but TcpListener and if you need a better performance, use Socket class directly.
At the Android client side, you should new Socket(server,servPort), when you want to send message, write the outputStream, and read the inputStream to receive message.