Simple client server java

Simple Java Client/Server Program

I’m writing my first java client/server program which just establishes a connection with the server sends it a sentence and the server sends the sentence back all capitalized. This is actually an example straight out of the book, and it works well and fine when I’m running the client and server on the same machine and using localhost for the server address. But when I put the client program on a different computer, it times out and never makes a connection with the server. I’m not sure why this is and its kind of lame making a your first client/server program and not actually be able to use it on two different machines. Here is the client code:

import java.io.*; import java.net.*; public class TCPClient < public static void main(String argv[]) throws Exception < String sentence; String modifiedSentence; BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); Socket clientSocket = new Socket("localhost", 6789); DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); sentence = inFromUser.readLine(); outToServer.writeBytes(sentence + '\n'); modifiedSentence = inFromServer.readLine(); System.out.println(modifiedSentence); clientSocket.close(); >> 
import java.io.*; import java.net.*; public class TCPServer < public static void main(String args[]) throws Exception < String clientSentence; String capitalizedSentence; ServerSocket welcomeSocket = new ServerSocket(6789); while(true) < Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); clientSentence = inFromClient.readLine(); capitalizedSentence = clientSentence.toUpperCase() + '\n'; outToClient.writeBytes(capitalizedSentence); >> > 

The only thing I change when I run it on two different machines is the client program makes its socket with the IP address of the machine with the server program (which I got from whatismyipaddress.com). Thanks a lot for any help. Update: I am indeed on a campus and it seems that its probably not allowing me to use that random port. Any suggestions on finding out what port I can use and or a port that is more than likely allowed?

Before try debugging the program perhaps try and make sure you can ping the other computer first. That way you know that the network isn’t to blame.

9 Answers 9

It’s probably a firewall issue. Make sure you port forward the port you want to connect to on the server side. localhost maps directly to an ip and also moves through your network stack. You’re changing some text in your code but the way your program is working is fundamentally the same.

try testing connection to your server with telnet from a client machine. If you get «connection refused» or timeout, that’s a firewall problem

If you’re at school, you almost certainly have a router. Ping won’t help much; it verifies that the machine is reachable, but not if your port is open. You could try using your browser to connect to the remote machine, you should get something back like «GET / HTTP 1.1». Or you could try something like curl.

Читайте также:  Ajax + PHP: пример | sitear.ru

There is a fundamental concept of IP routing: You must have a unique IP address if you want your machine to be reachable via the Internet. This is called a «Public IP Address». «www.whatismyipaddress.com» will give you this. If your server is behind some default gateway, IP packets would reach you via that router. You can not be reached via your private IP address from the outside world. You should note that private IP addresses of client and server may be same as long as their corresponding default gateways have different addresses (that’s why IPv4 is still in effect) I guess you’re trying to ping from your private address of your client to the public IP address of the server (provided by whatismyipaddress.com). This is not feasible. In order to achieve this, a mapping from private to public address is required, a process called Network Address Translation or NAT in short. This is configured in Firewall or Router. You can create your own private network (say via wifi). In this case, since your client and server would be on the same logical network, no private to public address translation would be required and hence you can communicate using your private IP addresses only.

If you got your IP address from an external web site (http://whatismyipaddress.com/), you have your external IP address. If your server is on the same local network, you may need an internal IP address instead. Local IP addresses look like 10.X.X.X, 172.X.X.X, or 192.168.X.X.

Try the suggestions on this page to find what your machine thinks its IP address is.

Instead of using the IP address from whatismyipaddress.com, what if you just get the IP address directly from the machine and plug that in? whatismyipaddress.com will give you the address of your router (I’m assuming you’re on a home network). I don’t think port forwarding will work since your request will come from within the network, not outside.

Are you on a campus network or something? They may have their switches/routers configured to block certain ports, even from within the network. If you can ping the other machine while this doesn’t work , that port may be blocked.

Источник

A Simple Client Server Socket Program

We will see how to communicate between a server and a client using simple network programming using sockets. You can get started with socket programming. Also, a simple client server program might be needed in many situations; you can just copy paste the basic code below and add to it.

We will create a simple server that accepts a client and sends a string message to the client. Client simply prints the message from server in the console.

Basic steps to create a server

  1. At the server side, create a server socket with some port number as:
    ServerSocket ss=new ServerSocket(777);
  2. Make the server wait till a client accepts connection, using accept() method as:
    Socket s=ss.accept();
  3. Get an OutputStream object using getOutputStream() method of Socket class. This stream is used by the socket to send data to the client.
    OutputStream os=s.getOutputStream();
  4. Send data to the client using a PrintStream wrapper:
    PrintStream ps=new PrintStream(os);
    ps.println(str);
  5. Finally, close the ServerSocket, Socket and PrintStream objects.
    ss.close();
    s.close();
    ps.close();
Читайте также:  How to Play Pause & Stop Audio file using JavaScript & HTML5

Basic steps to create a client

  1. Create a socket at the client side specifying the server ip addresss and port as:
    Socket s =new Socket(“IPaddress”,port_number);
  2. Add InputStream to the Socket to receive data on the InputStream
    InputStream is=s.getInputStream();
  3. Read the data from the Socket into the client using BufferedReader wrapper as
    BufferedReader br=new BufferedReader(new InputStreamReader(is));
  4. Read data from the BufferedReader using read() or readLine() methods.
    str=br.readLine();
  5. Finally, close the BufferedReader and the Socket
    br.close();
    s.close();

Code

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server public static void main(String[] args) throws IOException

System.out.println(«Server»);
ServerSocket ss = new ServerSocket(7777);
Socket s = ss.accept();
OutputStream os = s.getOutputStream();
PrintStream ps = new PrintStream(os);
ps.println(«Hello from server»);

ss.close();
s.close();
ps.close();
>
>

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client public static void main(String[] args) throws UnknownHostException,
IOException Socket s = new Socket(«mchej01», 7777);
InputStream is = s.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
System.out.println(«message:» + br.readLine());
br.close();
s.close();
>
>

Executing the code

  • Compile both classes
  • Run the Server first and you can see the server waiting for client.
  • Now run the Client and see the message sent from server print in the console.

This is a very simple program, but still let me know if you find any issues or have any doubts,

Источник

Java Socket Programming — Socket Server, Client example

Java Socket Programming - Socket Server, Client example

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Welcome to Java Socket programming example. Every server is a program that runs on a specific system and listens on a specific port. Sockets are bound to the port numbers and when we run any server it just listens on the socket and waits for client requests. For example, tomcat server running on port 8080 waits for client requests and once it gets any client request, it responds to them.

Java Socket Programming

java socket, java socket programming, java socket example

A socket is one endpoint of a two-way communication link between two programs running on the network. The socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent. In java socket programming example tutorial, we will learn how to write java socket server and java socket client program. We will also learn how server client program read and write data on the socket. java.net.Socket and java.net.ServerSocket are the java classes that implements Socket and Socket server.

Java Socket Server Example

package com.journaldev.socket; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.ClassNotFoundException; import java.net.ServerSocket; import java.net.Socket; /** * This class implements java Socket server * @author pankaj * */ public class SocketServerExample < //static ServerSocket variable private static ServerSocket server; //socket server port on which it will listen private static int port = 9876; public static void main(String args[]) throws IOException, ClassNotFoundException< //create the socket server object server = new ServerSocket(port); //keep listens indefinitely until receives 'exit' call or program terminates while(true)< System.out.println("Waiting for the client request"); //creating socket and waiting for client connection Socket socket = server.accept(); //read from socket to ObjectInputStream object ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); //convert ObjectInputStream object to String String message = (String) ois.readObject(); System.out.println("Message Received: " + message); //create ObjectOutputStream object ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); //write object to Socket oos.writeObject("Hi Client "+message); //close resources ois.close(); oos.close(); socket.close(); //terminate the server if client sends exit request if(message.equalsIgnoreCase("exit")) break; >System.out.println("Shutting down Socket server!!"); //close the ServerSocket object server.close(); > > 

Java Socket Client

package com.journaldev.socket; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; /** * This class implements java socket client * @author pankaj * */ public class SocketClientExample < public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException, InterruptedException< //get the localhost IP address, if server is running on some other IP, you need to use that InetAddress host = InetAddress.getLocalHost(); Socket socket = null; ObjectOutputStream oos = null; ObjectInputStream ois = null; for(int i=0; i<5;i++)< //establish socket connection to server socket = new Socket(host.getHostName(), 9876); //write to socket using ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); System.out.println("Sending request to Socket Server"); if(i==4)oos.writeObject("exit"); else oos.writeObject(""+i); //read the server response message ois = new ObjectInputStream(socket.getInputStream()); String message = (String) ois.readObject(); System.out.println("Message: " + message); //close resources ois.close(); oos.close(); Thread.sleep(100); >> > 

To test java socket programming of server-client communication, first we need to run SocketServerExample class. When you will run socket server, it will just print “Waiting for client request” and then wait for the client request. Now when you will run SocketClientExample class, it will send a request to java socket server and print the response message to console. Here is the output of java socket server SocketServerExample program.

Waiting for the client request Message Received: 0 Waiting for the client request Message Received: 1 Waiting for the client request Message Received: 2 Waiting for the client request Message Received: 3 Waiting for the client request Message Received: exit Shutting down Socket server!! 
Sending request to Socket Server Message: Hi Client 0 Sending request to Socket Server Message: Hi Client 1 Sending request to Socket Server Message: Hi Client 2 Sending request to Socket Server Message: Hi Client 3 Sending request to Socket Server Message: Hi Client exit 

That’s all for a quick roundup of Socket programming in java. I hope you can get started with java socket server and java socket client programming. Reference: Oracle Doc

Читайте также:  Получить id страницы wordpress php

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

Источник

Оцените статью