I have made two programs using Java that can communicate using Socket and They work fine on my own PC. But when I try to do the same thing between two computers, It does not work, as if the computers cannot find each other or something else. (I get the IP Address of the computer that works as the server using ipconfig in CMD)
What ever is wrong here, is not about the code. I even turned off the firewalls on both computers, but I nothing changed. Can anyone help me out?
MyServer.java
import java.io.*;
import java.net.*;
import java.util.*;
public class MyServer {
// Scanner Object
static Scanner scan = new Scanner(System.in);
// Objects
static ServerSocket serverSocket;
static Socket socket;
static DataInputStream dIs;
static DataOutputStream dOut;
public static void main(String[] args) {
try {
// Setting Up Message
System.out.println("Server Waiting For Connections...");
// Setup Server Socket
serverSocket = new ServerSocket(6666);
// Accept Client Connection Request
socket = serverSocket.accept();
// Confirmation Message
System.out.println("Client Connected.");
// Data Input Stream
dIs = new DataInputStream(socket.getInputStream());
// Data Output Stream
dOut = new DataOutputStream(socket.getOutputStream());
String Input = "";
while (!Input.equalsIgnoreCase("close Connection")) {
// Read Client Message
Input = dIs.readUTF();
System.out.print("\nClient: " + Input);
if (!Input.equalsIgnoreCase("close Connection")) {
// Send Server-Side Response
System.out.print("\nResponse: ");
dOut.writeUTF(scan.nextLine());
dOut.flush();
} else {
dOut.writeUTF("Connection Closed.");
dOut.flush();
}
}
closeConnections();
} catch (Exception ex) {
// Error Message
System.out.println("Error: " + ex);
closeConnections();
}
}
public static void closeConnections() {
try {
// Close Connection
dIs.close();
socket.close();
serverSocket.close();
System.out.println("Connection Closed.");
} catch (Exception ex) {
System.out.println("Could Not Close Connections.");
}
}
}
MyClient.java
import java.io.*;
import java.net.*;
import java.util.*;
public class MyClient {
// Scanner Object
static Scanner scan = new Scanner(System.in);
// Objects
static Socket socket;
static DataInputStream dIs;
static DataOutputStream dOut;
public static void main(String[] args) {
try {
// Setup Connection Socket For Client
socket = new Socket("localhost",6666);
// Data Input Stream
dIs = new DataInputStream(socket.getInputStream());
// Data Output Stream
dOut = new DataOutputStream(socket.getOutputStream());
String Input = "";
while (!Input.equalsIgnoreCase("Close Connection")) {
// Send Client-Side Message
System.out.print("\n- Client Message: ");
dOut.writeUTF(scan.nextLine());
dOut.flush();
// Read Server Message
Input = dIs.readUTF();
System.out.print("\nServer Response: " + Input);
}
closeConnections();
} catch (Exception ex) {
// Error Message
System.out.println(ex);
closeConnections();
}
}
public static void closeConnections() {
try {
// Close Connection
dIs.close();
dOut.close();
socket.close();
} catch (Exception ex) {
System.out.println("Could Not Close Connections.");
}
}
}
Related
A client connects successfully to the server and gets the message "Echo server started.." from the server but when writing to the server nothing happens. Im trying to create an Echo Client program that will connect to the Echo Server (which I assume is successful) now what's left is the communication between the client and the echo server. Any help with to point out the flaw will be appreciated!
Client:
import java.net.*;
import java.util.*;
import java.io.*;
public class GreetinEchoClient {
public static void main(String [] args) throws IOException
{
System.out.println("Echo client ...");
InetAddress localHost = InetAddress.getLocalHost();
Socket socket = new Socket(localHost, 7777);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("We are connected to echo server");
Scanner scanner = new Scanner(System.in);
while(true) {
System.out.println("Enter message :");
String input = scanner.nextLine();
if("exit".equalsIgnoreCase(input)) {
break;
}
out.println(input);
String response = br.readLine();
System.out.println("Server response :" + response);
} try {
socket.close();
scanner.close();
}catch (IOException e) {}
}
Echo server:
import java.io.*;
import java.net.*;
public class GreetinEcho {
public static void main(String [] args) {
ServerSocket echoServer = null;
String line;
DataInputStream is;
DataOutputStream os;
Socket clientSocket = null;
try {
echoServer = new ServerSocket(7777);
System.out.println("Echo Server Started....");
}
catch (IOException e) {
System.out.println(e);
}
try {
clientSocket = echoServer.accept();
System.out.println("Connected to the client " + clientSocket.getRemoteSocketAddress());
is = new DataInputStream(clientSocket.getInputStream());
os = new DataOutputStream(clientSocket.getOutputStream());
while(true) {
line = is.readUTF();
System.out.println("On Server :" + line);
os.writeUTF(line);
}
} catch (IOException e) {
System.out.println(e);
}
}
}
i'm still trying to study on socket server and client programming. So i did this coding based on the tutorial i received. I managed to create thread for multi client interaction. However, i could not stop the loop in the in the client handler that keep displaying welcoming message that i made even after i made case for it.
How to stop the looping of welcoming message that has been made?
Server side
public class server {
public static void main(String[] args) throws IOException{
//server listen on port 4999
ServerSocket ss = new ServerSocket(4999);
//running loop to get client request
while(true){
Socket s = null;
try
{
//socket object receive incoming client requests
s = ss.accept();
System.out.println("New Client is connected :" + s);
//Obtaining input and out streams
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
System.out.println("Assigning new thread for this client");
//create new thread object
Thread t = new ClientHandler(s, dis, dos);
//Invoking start() method
t.start();
}
catch (Exception e){
s.close();
e.printStackTrace();
}
}
}
}
class ClientHandler extends Thread{
DateFormat fordate= new SimpleDateFormat("yyyy/MM/dd");
DateFormat fortime = new SimpleDateFormat("yyyy/MM/dd");
final DataInputStream dis;
final DataOutputStream dos;
final Socket s;
//Constructor
public ClientHandler(Socket s, DataInputStream dis,DataOutputStream dos){
this.s = s;
this.dis = dis;
this.dos = dos;
}
#Override
public void run() {
String received;
String toreturn;
while(true){
try{
//ask user his position
dos.writeUTF("WELCOME TO CREWCUTS SOCKET SERVER. \n" +
"Select either [Customer | BarberShop] \n" +
"Type Exit to terminate connection");
//get client's answer
received = dis.readUTF();
if(received.equals("Exit")){
System.out.println("Client " + this.s + "send exit");
System.out.println("Closing connection");
this.s.close();
System.out.println("Connection closed");
break;
}
//creating Date object
Date date = new Date();
//write on output stream based on the answer from client
switch (received){
case "Customer" :
toreturn = fordate.format(date);
dos.writeUTF(toreturn + "\n Welcome to Customer service of CREWCUTS Socket Server");
break;
case "BarberShop" :
toreturn = fordate.format(date);
dos.writeUTF(toreturn +"\n Welcome to BarberShop service of CREWCUTS Socket Server");
break;
default:
dos.writeUTF("Invalid input");
break;
}
}
catch (IOException e) {
e.printStackTrace();
}
}
try
{
//closing resource
this.dis.close();
this.dos.close();
}
catch(IOException e){
e.printStackTrace();
}
}
}
Client Side
public class client {
public static void main(String[] args) throws IOException{
try{
Scanner scn = new Scanner(System.in);
//establish connection to server port 4999 in localhost
Socket s = new Socket("localhost" ,4999);
//obtaining input and out streams
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
//loop for exchange of information between client and client handler
while(true)
{
System.out.println(dis.readUTF());
String tosend = scn.nextLine();
dos.writeUTF(tosend);
//if client send Exit, connection closed and break from loop
if(tosend.equals("Exit")){
System.out.println("Closing connection : " + s);
s.close();
System.out.println("Connection closed");
break;
}
//printing info as requested by client
String received = dis.readUTF();
System.out.println(received);
}
//closing resources
scn.close();
dis.close();
dos.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}
Just remove the welcome message out of loop both in client and server as below.
server.java
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.io.*;
import java.net.*;
public class server {
public static void main(String[] args) throws IOException{
//server listen on port 4999
ServerSocket ss = new ServerSocket(4999);
//running loop to get client request
while(true){
Socket s = null;
try
{
//socket object receive incoming client requests
s = ss.accept();
System.out.println("New Client is connected :" + s);
//Obtaining input and out streams
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
System.out.println("Assigning new thread for this client");
//create new thread object
Thread t = new ClientHandler(s, dis, dos);
//Invoking start() method
t.start();
}
catch (Exception e){
s.close();
e.printStackTrace();
}
}
}
}
class ClientHandler extends Thread{
DateFormat fordate= new SimpleDateFormat("yyyy/MM/dd");
DateFormat fortime = new SimpleDateFormat("yyyy/MM/dd");
final DataInputStream dis;
final DataOutputStream dos;
final Socket s;
//Constructor
public ClientHandler(Socket s, DataInputStream dis,DataOutputStream dos){
this.s = s;
this.dis = dis;
this.dos = dos;
}
#Override
public void run() {
String received;
String toreturn;
//ask user his position
try{
dos.writeUTF("WELCOME TO CREWCUTS SOCKET SERVER. \n" +
"Select either [Customer | BarberShop] \n" +
"Type Exit to terminate connection");
}
catch (IOException e) {
e.printStackTrace();
}
while(true){
try{
//get client's answer
received = dis.readUTF();
if(received.equals("Exit")){
System.out.println("Client " + this.s + "send exit");
System.out.println("Closing connection");
this.s.close();
System.out.println("Connection closed");
break;
}
//creating Date object
Date date = new Date();
//write on output stream based on the answer from client
switch (received){
case "Customer" :
toreturn = fordate.format(date);
dos.writeUTF(toreturn + "\n Welcome to Customer service of CREWCUTS Socket Server");
break;
case "BarberShop" :
toreturn = fordate.format(date);
dos.writeUTF(toreturn +"\n Welcome to BarberShop service of CREWCUTS Socket Server");
break;
default:
dos.writeUTF("Invalid input");
break;
}
}
catch (IOException e) {
e.printStackTrace();
}
}
try
{
//closing resource
this.dis.close();
this.dos.close();
}
catch(IOException e){
e.printStackTrace();
}
}
}
client.java
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.io.*;
import java.util.Scanner;
import java.net.*;
public class client {
public static void main(String[] args) throws IOException{
try{
Scanner scn = new Scanner(System.in);
//establish connection to server port 4999 in localhost
Socket s = new Socket("localhost" ,4999);
//obtaining input and out streams
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
try{
System.out.println(dis.readUTF());
}
catch (Exception e){
e.printStackTrace();
}
//loop for exchange of information between client and client handler
while(true)
{
String tosend = scn.nextLine();
dos.writeUTF(tosend);
//if client send Exit, connection closed and break from loop
if(tosend.equals("Exit")){
System.out.println("Closing connection : " + s);
s.close();
System.out.println("Connection closed");
break;
}
//printing info as requested by client
String received = dis.readUTF();
System.out.println(received);
}
//closing resources
scn.close();
dis.close();
dos.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}
The program is intended to have multiple clients connect to a single server and the clients are able to send and receive messages among other clients.
For example if Client A says "Hi", Client B and Client C connected to the server would also receive "Hi".
In my current code, the server only receives the messages sent by the clients.
I'm currently looking for a solution to have the server broadcast the message sent by a client (eg. ClientA) to other clients. Any advice would be much appreciated.
This server class handles the connections of multiple clients with the use of threads:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
class EchoThread extends Thread {
private Socket socket;
//constructor
public EchoThread(Socket clientSocket) {
this.socket = clientSocket;
}
#Override
public void run() {
DataInputStream inp = null;
try {
inp = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
//print whatever client is saying as long as it is not "Over"
String line = "";
while (!line.equals("Over")) {
try {
line = inp.readUTF();
System.out.println(line);
} catch (IOException e) { System.out.println(e); }
}
//closes connection when client terminates the connection
System.out.print("Closing Connection");
socket.close();
} catch (IOException e) { System.out.println(e); }
}
}
public class Server {
private static final int PORT = 5000;
public static void main(String args[]) {
ServerSocket serverSocket = null;
Socket socket = null;
//starts the server
try {
serverSocket = new ServerSocket(PORT);
System.out.println("Server started");
System.out.println("Waiting for a client ...\n");
} catch (IOException e) { System.out.println(e); }
//while loop to accept multiple clients
int count = 1;
while(true) {
try {
socket = serverSocket.accept();
System.out.println("Client " + count + " accepted!");
count++;
} catch (IOException e) { System.out.println(e); }
//starts the server thread
new EchoThread(socket).start();
}
}
}
and this is the client class (I have multiple instances of this code running):
import java.net.*;
import java.io.*;
public class ClientA {
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream output = null;
public ClientA(String address, int port) {
//establish connection
try {
socket = new Socket(address, port);
System.out.println("Connected");
//takes input from terminal
input = new DataInputStream(System.in);
//sends output to the socket
output = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) { System.out.println(e); }
//string to read message from input
String line = "";
//keep reading until "Over" is input
while (!line.equals("Over")) {
try {
line = input.readLine();
output.writeUTF(line);
} catch (IOException e) { System.out.println(e); }
}
//close the connection
try {
input.close();
output.close();
socket.close();
} catch (IOException e) { System.out.println(e); }
}
public static void main (String args[]) {
ClientA client = new ClientA("127.0.0.1", 5000);
}
}
Do feel free to correct me on my code comments as I'm still not very familiar with socket programming.
You did well. Just add a thread to receive message in ClientA; and store socket clients in Server.
In fact, Server is also a "client" when is send message to client.
I add some code based on your code. It works well, hope it's helpful.
class EchoThread extends Thread {
//*****What I add begin.
private static List<Socket> socketList = new ArrayList<>();
//*****What I add end.
private Socket socket;
//constructor
public EchoThread(Socket clientSocket) {
this.socket = clientSocket;
socketList.add(socket);
}
#Override
public void run() {
DataInputStream inp = null;
try {
inp = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
//print whatever client is saying as long as it is not "Over"
String line = "";
while (!line.equals("Over")) {
try {
line = inp.readUTF();
System.out.println(line);
//*****What I add begin.
sendMessageToClients(line);
//*****What I add end.
} catch (IOException e) { System.out.println(e); break;}
}
//closes connection when client terminates the connection
System.out.print("Closing Connection");
socket.close();
} catch (IOException e) { System.out.println(e); }
}
//*****What I add begin.
private void sendMessageToClients(String line) throws IOException {
for (Socket other : socketList) {
if (other == socket) {
continue;//ignore the sender client.
}
DataOutputStream output = new DataOutputStream(other.getOutputStream());
output.writeUTF(line);
}
}
//*****What I add end.
}
public class ClientA {
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream output = null;
public ClientA(String address, int port) {
//establish connection
try {
socket = new Socket(address, port);
System.out.println("Connected");
//takes input from terminal
input = new DataInputStream(System.in);
//sends output to the socket
output = new DataOutputStream(socket.getOutputStream());
//*****What I add begin.
//Here create a thread to receive message from server.
DataInputStream inp = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
new Thread(() -> {
while (true) {
String str;
try {
str = inp.readUTF();
System.out.println(str);
} catch (IOException e) {
e.printStackTrace();//error.
break;
}
}
}, "Client Reveiver.").start();
//*****What I add end.
} catch (IOException e) { System.out.println(e); }
//string to read message from input
String line = "";
//keep reading until "Over" is input
while (!line.equals("Over")) {
try {
line = input.readLine();
output.writeUTF(line);
} catch (IOException e) { System.out.println(e); }
}
//close the connection
try {
input.close();
output.close();
socket.close();
} catch (IOException e) { System.out.println(e); }
}
I would have a single server thread which would maintain a register of the clients, possibly in a concurrent collection. Then I would send each message received from a client to all other clients.
I'm new in network developing in Java and I want to create a simple Socket server, that get values from client and collects all of them in ArrayList. I wrote an example code, but in server side it not collecting the strings. This is my server side:
Server
public class ServerSideSocket extends Thread{
private ServerSocket serverSocket;
private Socket socket;
private ArrayList<String> list = new ArrayList<String>();
DataInputStream inData;
DataOutputStream outData;
public ServerSideSocket(int port) throws IOException {
serverSocket = new ServerSocket(port);
}
public void run() {
while(true) {
try{
System.out.println("Waiting for connection...");
socket = serverSocket.accept();
System.out.println("Connected!" );
inData = new DataInputStream(socket.getInputStream());
outData = new DataOutputStream(socket.getOutputStream());
System.out.println(inData.readUTF());
list.add(inData.readUTF());
System.out.println("------------ VALUES ---------");
for (String value: list) {
System.out.println(value);
}
System.out.println("------------ END VALUES ---------");
outData.writeUTF("Message saved!");
outData.flush();
} catch (SocketException ex) {
ex.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inData.close();
outData.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
int port = 9999;
try {
Thread t = new ServerSideSocket(port);
t.start();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
and Client:
public class ClientSideSocket {
public static void main(String[] args) {
String serverName = "localhost";
int port = 9999;
String line = "";
try {
System.out.println("Connecting to " + serverName + " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to " + client.getRemoteSocketAddress());
OutputStream out = client.getOutputStream();
DataOutputStream outData = new DataOutputStream(out);
InputStream in = client.getInputStream();
DataInputStream inData = new DataInputStream(in);
outData.writeUTF("Simple text");
outData.flush();
System.out.println("Response from server: " + inData.readUTF());
System.out.println("You can write more messages!");
System.out.println();
client.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
what is wrong in my code?
This happens because you try to read twice from the data stream by calling inData.readUTF() method. First call successfully reads data from the stream, but instead of saving result you try to perform another read 2 lines below.
readUTF() is blocking method and thus it waits for another portion of data which never comes from the same client. That's why your server hungs forever
What you want to do is to read once and store result into local variable:
String res = inData.readUTF();
list.add(res);
You are writing data once as "Simple Text" which you can read only once.
Where in your code you are first reading it
System.out.println(inData.readUTF());
list.add(inData.readUTF());
Instead of this you should first store it in a String and then use it.
String message = inData.readUTF();
System.out.println(message);
list.add(message);
i am creating a simple client server communication . but i am unable to type anything in the command prompt.
code for server
i am unable to type anything in cmd when i run program
import java.net.*;
import java.io.*;
public class Tests
{
public static void main(String args[])
{
try
{
ServerSocket server = new ServerSocket(3000);
Socket c = server.accept();
DataOutputStream out = new DataOutputStream(c.getOutputStream());
DataInputStream in = new DataInputStream(c.getInputStream());
DataInputStream console = new DataInputStream(System.in);
String input,output;
while (true)
{
input = in.readLine();
System.out.println("Client says: " + input);
output = console.readLine();
out.writeBytes(output+ '\n');
}
}
catch(IOException e)
{ System.out.println("IO Error in streams " + e); }
}
}
code for client
please help me
import java.io.*;
import java.net.*;
public class Testc
{
public static void main(String[] args)
{
try
{
Socket client = new Socket("127.0.0.1", 3000);
DataOutputStream out = new DataOutputStream(client.getOutputStream());
DataInputStream in = new DataInputStream(client.getInputStream());
DataInputStream console = new DataInputStream(System.in);
System.out.println("Connected. Enter text:");
String input,output;
while (true)
{
input = in.readLine();
System.out.println("server says : "+ input);
output = console.readLine();
out.writeBytes(output + '\n');
}
}
catch (UnknownHostException e)
{ System.err.println("error"); }
catch (IOException e)
{ System.err.println("I/O error"); }
}
}