I'm trying to make a connection between a client and server in java but when I run the server it gives a "Connection refused: connect" I don't know what to do and I'm really new to java networking can you please help me? here's my server code:
class reserver {
static int serverPort = 6667;
static int serverPort1 = 6668;
static String Message,input;
String ip = "127.0.0.1";
public reserver(){
try{
InetAddress ipAddress = InetAddress.getByName(ip);
Socket socket = new Socket(ipAddress,serverPort);
OutputStream sout = socket.getOutputStream();
InputStream sin = socket.getInputStream();
DataOutputStream out = new DataOutputStream(sout);
out.writeUTF(input);
out.flush();
}catch(IOException e){
System.out.print(e.getMessage());
}
}
public static void main(String [] args){
new reserver();
try{
ServerSocket ss = new ServerSocket(serverPort1);
int i = 0;
while(true){
i++;
Socket socket = ss.accept();
OutputStream sout = socket.getOutputStream();
InputStream sin = socket.getInputStream();
DataInputStream in = new DataInputStream(sin);
DataOutputStream out = new DataOutputStream(sout);
input = in.readUTF();
System.out.println("Message [" + i + "]" +input);
}
}catch(IOException e){
System.out.print(e.getMessage());
}
}
}
And here's my clients code:
class reclient {
String ip = "127.0.0.1";
static int serverPort = 6667;
static int serverPort1 = 6668;
static String Message,input;
public reclient(){
try{
Scanner s = new Scanner(System.in);
System.out.print("Enter Text: ");
input = s.nextLine();
InetAddress ipAddress = InetAddress.getByName(ip);
Socket socket = new Socket(ipAddress,serverPort);
OutputStream sout = socket.getOutputStream();
InputStream sin = socket.getInputStream();
DataInputStream in = new DataInputStream(sin);
DataOutputStream out = new DataOutputStream(sout);
out.writeUTF(input);
out.flush();
}catch(IOException e){
System.out.print(e.getMessage());
}
}
public static void main(String [] args){
new reclient();
try{
ServerSocket ss = new ServerSocket(serverPort1);
int i = 0;
while(true){
i++;
Socket socket = ss.accept();
OutputStream sout = socket.getOutputStream();
InputStream sin = socket.getInputStream();
DataInputStream in = new DataInputStream(sin);
DataOutputStream out = new DataOutputStream(sout);
input = in.readUTF();
System.out.println("Message [" + i + "]" +input);
}
}catch(IOException e){
System.out.print(e.getMessage());
}
}
}
It looks like your code is swapped for server and client.
Look at :
how do i connect to the server socket using the ip address and port number( client is running on a different machine than server)
Related
The problem i have is that when i open a second client, the server doesn't seem to detect that a second client was opened. With the first time the client being opened it works fine and the server detects that a client has been connected.
Server:
public class Server {
Socket previousSocket = null;
private static int port = 9001;
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("[SERVER] Server successfully launched on port: " + port);
DatagramSocket UDPSocket = new DatagramSocket(9002);
Socket previousSocket = null;
while (true) {
Socket newSocket = serverSocket.accept();
System.out.println("new client connected");
if (previousSocket == null) {
previousSocket = newSocket;
System.out.println("1 st client");
} else {
System.out.println("2 nd client");
previousSocket = null;
}
byte[] data = new byte[500];
DatagramPacket received = new DatagramPacket(data, data.length);
while(true) {
UDPSocket.receive(received);
String receivedData = new String(received.getData());
System.out.println(receivedData);
}
}
}
}
Client:
public ChatClient() throws UnknownHostException, IOException {
Socket socket = new Socket("127.0.0.1", 9001);
Scanner scanner = new Scanner(System.in);
DatagramSocket UDPSocket = new DatagramSocket();
while(scanner.hasNextLine()) {
String message = scanner.nextLine();
InetAddress ip = InetAddress.getByName("127.0.0.1");
DatagramPacket packet = new DatagramPacket(message.getBytes(), message.getBytes().length, ip, 9002);
UDPSocket.send(packet);
}
}
The following loop will never end, that's the reason for your problem
while(true) {
UDPSocket.receive(received);
String receivedData = new String(received.getData());
System.out.println(receivedData);
}
I have tomcat installed on vps, everything has been configured, but how do I host my java server on it? What extension should I use and which folder should I put? Or do I need to change something in the Server.java?
Here he is:
public class Server {
public static void main(String[] ar) throws IOException {
int port = 8080;
try {
ServerSocket ss = new ServerSocket(port);
System.out.println("Waiting for a client...");
Socket socket = ss.accept();
System.out.println("Got a client!");
System.out.println();
InputStream sin = socket.getInputStream();
OutputStream sout = socket.getOutputStream();
DataInputStream in = new DataInputStream(sin);
DataOutputStream out = new DataOutputStream(sout);
String line = null;
while(true) {
line = in.readUTF();
System.out.println("The dumb client just sent me this line : " + line);
System.out.println("I'm sending it back...");
out.writeUTF(line);
out.flush();
System.out.println("Waiting for the next line...");
System.out.println();
}
} catch(Exception x) { x.printStackTrace(); }
}
}
Client program
public class client implements Runnable {
protected static String server_IP = "141.117.57.42";
private static final int server_Port = 5555 ;
protected static String client_IP ;
public static void main(String[] args) throws IOException{
final String host = "localhost";
int init = 0 ;
try {
InetAddress iAddress = InetAddress.getLocalHost();
client_IP = iAddress.getHostAddress();
System.out.println("Current IP address : " +client_IP);
} catch (UnknownHostException e) {
}
try {System.out.println("hello1");
Socket socket = new Socket(server_IP,server_Port);
System.out.println("hello3");
init = initialize(socket);
}catch (SocketException e) {
System.out.println("Error: Unable to connect to server port ");
}
if (init == 0 ){
System.out.println("error: Failed to initialize ");
System.exit(0);
}
//Thread init_Thread = new Thread();
}
private static int initialize(Socket socket ) throws IOException{
System.out.println("hello");
int rt_value = 0 ;
OutputStream os = socket.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter pw = new PrintWriter(os, true);
System.out.println("server: " + br.readLine());
pw.println("192.343.34.321");
// BufferedReader userInputBR = new BufferedReader(new InputStreamReader(System.in));
//String userInput = userInputBR.readLine();
//out.println(userInput);
socket.close();
return rt_value = 1 ;
}
public void run(){
}
}
server side program
public class server {
protected static String server_IP ;
public static void main(String[] args) throws IOException {
int server_Port = 5555 ;
try {
InetAddress iAddress = InetAddress.getLocalHost();
server_IP = iAddress.getHostAddress();
System.out.println("Server IP address : " +server_IP);
} catch (UnknownHostException e) {
}
ServerSocket serverSocket = new ServerSocket(server_Port);
while (true) {
Socket socket = serverSocket.accept();
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
InputStreamReader isr = new InputStreamReader(socket.getInputStream());
pw.println("Connection confirmed ");
BufferedReader br = new BufferedReader(isr);
String str = br.readLine();
pw.println("your ip address is " + str);
pw.close();
//socket.close();
//System.out.println("Just said hello to:" + str);
}
How do I connect to the server socket using the ip address and port number (client is running on a different machine than server).
When I change the server_IP in client to "local host", it works perfectly.
To connect in your code you use:
Socket socket = new Socket(server_IP,server_Port);
So you could use:
Socket socket = new Socket("192.168.1.4", 5555);
It looks like you have this in your code so I'm not sure what problem you're having.
Don't forget that you have to setup your router to forward ports if it is located outside of your local network.
http://www.wikihow.com/Set-Up-Port-Forwarding-on-a-Router
Don't forget that if you are running a firewall, this can also interfere with the connection.
Update /etc/hosts
Add following line
127.0.1.1 192.168.10.109
There are lot of close_wait connection, when ever a client client sends the message to the server and comes out the TCP FSM stuck in the CLOSE_WAIT STATE
This the Client code,
public class Client1
{
private static Socket socket;
public static void main(String args[])
{
try
{
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String number = "2";
String sendMessage = number + "\n";
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+sendMessage);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : " +message);
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
This the Server code which listen to the upcoming connection
public class Server1
{
private static Socket socket;
public static void main(String[] args)
{
try
{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");
//Server is running always. This is done using this while(true) loop
while(true)
{
//Reading the message from the client
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String number = br.readLine();
System.out.println("Message received from client is "+number);
//Multiplying the number by 2 and forming the return message
String returnMessage;
try
{
int numberInIntFormat = Integer.parseInt(number);
int returnValue = numberInIntFormat*2;
returnMessage = String.valueOf(returnValue) + "\n";
}
catch(NumberFormatException e)
{
//Input was not a number. Sending proper message back to client.
returnMessage = "Please send a proper number\n";
}
//Sending the response back to the client.
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Message sent to the client is "+returnMessage);
bw.flush();
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
socket.close();
}
catch(Exception e){}
}
}
}
The output TCP FSM
-bash:~$ netstat -an | grep 25000
tcp4 0 0 127.0.0.1.25000 127.0.0.1.56459 CLOSE_WAIT
tcp46 0 0 *.25000 *.* LISTEN
You're closing the accepted socket in the wrong place. It needs to be inside the accept loop.
public class JavaApplication15 {
public static String ip="127.0.0.1";
public static int port=5060;
public static void main(String[] args) throws IOException {
ServerSocket ss = null;
InetAddress ii = InetAddress.getLocalHost();
System.out.println(ii);
InetAddress ad = InetAddress.getByName(ip);
System.out.println(ad);
InetAddress i = ad;
System.out.println(i);
try {
// TODO code application logic here
ss = new ServerSocket();
ss.bind(new InetSocketAddress(ip, port));
InetSocketAddress ia;
String st=ss.getLocalSocketAddress().toString(); // print socket ip and address
System.out.println(st);
System.out.println("created");
} catch (IOException ex) {
System.out.println("not created");
}
Socket client = null,ee = null;
client = ss.accept();
PrintWriter out = null;
BufferedReader in = null ;
out = new PrintWriter(client.getOutputStream(),true);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String input = null;
while((input = in.readLine())!=null){
System.out.println(input);
System.out.println("echo :" +in.readLine());
}
out.flush();
in.close();
stdin.close();
client.close();
ss.close();
}
}
}
In this code server is being created and trying to establish a connection with socket. I think this code should show output but it is not showing. For example: if i say hello in the console , it should print hello. But it is not doing that. Can anyone help me what is actually going on here ???