Multi Client Simple Chat(non-GUI) Server in Java using threads - java

I am unable to figure out how to stop the message from appearing twice on both the client's screen.
The Actual output should be something like this:
Steps for Running the code:
1. Run Server on one terminal
2. Run two clients on two different terminals
When I run the Server - main method creates a Server object:
public static void main(String[] args) throws IOException {
Server server = new Server();
}
Server Constructor:
Server() throws IOException {
Date dNow = new Date();
System.out.println("MultiThreadServer started at " + String.format("%tc", dNow));
System.out.println();
ServerSocket server = new ServerSocket(8000);
ClientSockets = new Vector<Socket>();
while (true) {
Socket client = server.accept();
AcceptClient acceptClient = new AcceptClient(client);
System.out.println("Connection from Socket " + "[addr = " + client.getLocalAddress() + ",port = "
+ client.getPort() + ",localport = " + client.getLocalPort() + "] at "
+ String.format("%tc", dNow));
System.out.println();
//System.out.println(clientCount);
}
//server.close();
}
I am using Socket to connect to the server. Here is my Server code.
Server.java
import java.io.IOException;
import java.net.*;
import java.util.Vector;
import java.io.*;
import java.util.*;
import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.time.LocalDateTime;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.text.*;
import java.util.Scanner;
public class Server {
static Vector<Socket> ClientSockets;
int clientCount = 0;
//int i = 0;
Server() throws IOException {
Date dNow = new Date();
System.out.println("MultiThreadServer started at " + String.format("%tc", dNow));
System.out.println();
ServerSocket server = new ServerSocket(8000);
ClientSockets = new Vector<Socket>();
while (true) {
Socket client = server.accept();
AcceptClient acceptClient = new AcceptClient(client);
System.out.println("Connection from Socket " + "[addr = " + client.getLocalAddress() + ",port = "
+ client.getPort() + ",localport = " + client.getLocalPort() + "] at "
+ String.format("%tc", dNow));
System.out.println();
//System.out.println(clientCount);
}
//server.close();
}
public static void main(String[] args) throws IOException {
Server server = new Server();
}
class AcceptClient extends Thread {
Socket ClientSocket;
DataInputStream din;
DataOutputStream dout;
AcceptClient(Socket client) throws IOException {
ClientSocket = client;
din = new DataInputStream(ClientSocket.getInputStream());
dout = new DataOutputStream(ClientSocket.getOutputStream());
//String LoginName = din.readUTF();
//i = clientCount;
clientCount++;
ClientSockets.add(ClientSocket);
//System.out.println(ClientSockets.elementAt(i));
//System.out.println(ClientSockets.elementAt(1));
start();
}
public void run() {
try {
while (true) {
String msgFromClient = din.readUTF();
System.out.println(msgFromClient);
for (int i = 0; i < ClientSockets.size(); i++) {
Socket pSocket = (Socket) ClientSockets.elementAt(i);
DataOutputStream pOut = new DataOutputStream(pSocket.getOutputStream());
pOut.writeUTF(msgFromClient);
pOut.flush();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Client.java
import java.net.Socket;
import java.util.Scanner;
import java.io.*;
import java.net.*;
public class Client implements Runnable{
Socket socketConnection;
DataOutputStream outToServer;
DataInputStream din;
Client() throws UnknownHostException, IOException {
socketConnection = new Socket("127.0.0.1", 8000);
outToServer = new DataOutputStream(socketConnection.getOutputStream());
din = new DataInputStream(socketConnection.getInputStream());
Thread thread;
thread = new Thread(this);
thread.start();
BufferedReader br = null;
String ClientName = null;
Scanner input = new Scanner(System.in);
String SQL = "";
try {
System.out.print("Enter you name: ");
ClientName = input.next();
ClientName += ": ";
//QUERY PASSING
br = new BufferedReader(new InputStreamReader(System.in));
while (!SQL.equalsIgnoreCase("exit")) {
System.out.println();
System.out.print(ClientName);
SQL = br.readLine();
//SQL = input.next();
outToServer.writeUTF(ClientName + SQL);
//outToServer.flush();
//System.out.println(din.readUTF());
}
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] arg) throws UnknownHostException, IOException {
Client client = new Client();
}
public void run() {
while (true) {
try {
System.out.println("\n" + din.readUTF());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

The reason you have this is because you're sending the server whatever the client has written in the console, and the server sends it back to all of the clients (including the sender).
So you're writing a message in the console (and you see it) and then you're receiving it back as one of the clients (and you see it again).
A simple fix would be not to send the just received message back to the client (he already sees it in the console). Add this to the Server.AcceptClient#run method:
for (int i = 0; i < ClientSockets.size(); i++) {
Socket pSocket = (Socket) ClientSockets.elementAt(i);
if(ClientSocket.equals(pSocket)){
continue;
}
...

Related

TCP Client/Server program getting stuck when

I have been working on creating a program where communication can be exchanged between a server and a client using to program files in java. However, when I try to send messages from server to client. I have been working on a project where I am trying to send a message from a server to a client. However, when I put in my message, from the server, the client seems to get stuck on sentence = inFromServer.readLine(); in the client portion of my code and I'm not sure why. I ran the debugger on this, and it seems that "sentence" takes in the value that was inputted from the client, so im not sure why it get stuck. Does anyone have an idea what the problem may be?
Here's my code for reference-
Server Code:
package com.company;
import java.io.*;
import java.net.*;
import java.util.Scanner;
import java.util.concurrent.*;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
class threading implements Runnable {
private int portnumbers;
Socket clientsocket;
ServerSocket connectorsocket;
public threading(Socket clientsocket)
{
this.clientsocket = clientsocket;
}
public void run(){
try {
Serverstuff(this.clientsocket);
}
catch(Exception ex)
{
System.out.print("I found exception" + ex);
}
}
public void Serverstuff(Socket socketlol)
{
// File h = null;
int width = 1536;
int height = 2048;
BufferedImage image = null;
File f = null;
while(true) {
try {
String sentence1;
//Wait on welcoming socket for client
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(socketlol.getInputStream()));
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
DataOutputStream outToClient = new DataOutputStream(socketlol.getOutputStream());//create input stream, attached to socket
System.out.println("Flag1");
sentence1 = inFromUser.readLine();
System.out.println("Flag2");
System.out.println("Flag3");
outToClient.writeBytes(sentence1);
}
catch(Exception ex)
{
System.out.print("I found exception" + ex);
}
}
}
}
public class server{
public static void main(String argv[]) throws Exception {
String clientSentence;
String capitalizedSentence;
int portnumber;
Scanner scanney = new Scanner(System.in);
System.out.println("Enter the number of clients");
String arg1 = scanney.next();
int arg2 = Integer.parseInt(arg1);
int[] socketarray = new int[arg2];
for(int i = 0; i < arg2; i++) {
System.out.println("enter the port number");
String portnumberstr = scanney.next();
portnumber = Integer.parseInt(portnumberstr);
socketarray[i] = portnumber;
}
//ServerSocket welcomeSocket = new ServerSocket(5000);
int g = 0;
int whatever;
//ServerSocket welcomeSocket2 = new ServerSocket(5001);
while (true) {
if(g < arg2) {
System.out.println("Flagwhile1");
whatever = socketarray[g];
ServerSocket welcomeSocket = new ServerSocket(whatever);
System.out.println("Flagwhile2");
Socket clientsock = welcomeSocket.accept();
threading newthread = new threading(clientsock);
System.out.println("Flagwhile3");
new Thread(newthread).start();
g = g + 1;
}
}
}
}
Client Code:
package com.company;
import java.io.*;
import java.net.*;
import java.util.Scanner;
import java.util.concurrent.*;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class client2{
public static void main(String argv[]) throws Exception {
try {
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); //Create input stream
Socket clientSocket = new Socket("127.0.0.2", 5001); //Create client socket connect to server
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); //Create output stream, attached to socket
System.out.println("Flag19");
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); //Create input stream attached to socket
System.out.println("Flag20");
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n'); //send line to server
System.out.println("Flag21");
sentence = inFromServer.readLine();
System.out.println("Flag22");
System.out.println(sentence);
int test = 5;
clientSocket.close();
}
catch(IOException e){
System.out.println("Error: " + e);
}
}
}

Java basic concurrent communicator - does not fully accept connection

I want to create simple communicator with one server and few clients who could connect and send data to it. It works fine without any threads, with only one client, but once i try to incorporate concurrency it doesn't work. From client perspective there is some connection, I can send data, but there is no sign of receiving that data on server. Here is the server class:
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class MyServerSocket implements Runnable
{
private ServerSocket serverSocket;
public MyServerSocket() throws Exception
{
Random generator = new Random();
this.serverSocket = new ServerSocket(generator.nextInt(65000 - 60000) + 60000, 50, InetAddress.getByName("192.168.0.105"));
}
public InetAddress getSocketIPAddress()
{
return this.serverSocket.getInetAddress();
}
public int getPort()
{
return this.serverSocket.getLocalPort();
}
public void run()
{
while (true)
{
System.out.println("Running a thread");
try
{
String data = null;
Socket client = this.serverSocket.accept();
String clientAddress = client.getInetAddress().getHostName();
System.out.println("Connection from: " + clientAddress);
System.out.println("Here I am");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
String message = "";
while ((data = in.readLine()) != null && data.compareToIgnoreCase("quit") != 0)
{
message = ("\r\nMessage from " + clientAddress + ": " + data);
System.out.println(message);
out.write(message);
}
} catch (Exception e)
{
System.out.println("Something went wrong");
} finally
{
try
{
serverSocket.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
Server main:
import java.lang.Thread;
public class Main
{
public static void main(String[] args)
{
try
{
MyServerSocket socket = new MyServerSocket();
Runnable runnable = new MyServerSocket();
System.out.println("Port number: " + socket.getPort() + " IP address: " + socket.getSocketIPAddress());
Thread thread = new Thread(runnable);
thread.start();
}catch (Exception e)
{
e.printStackTrace();
}
}
}
Client class:
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class ClientSocket
{
private Socket socket;
private Scanner scanner;
ClientSocket(InetAddress serverAddress, int serverPort) throws Exception
{
this.socket = new Socket(serverAddress, serverPort);
this.scanner = new Scanner(System.in);
}
public void sendData() throws Exception
{
String data;
System.out.println("Please type in the message. If you want to terminate the connection, type Quit");
PrintWriter out = new PrintWriter(this.socket.getOutputStream(), true);
do
{
data = scanner.nextLine();
out.println(data);
out.flush();
}while(data.compareToIgnoreCase("quit") != 0);
out.println();
}
}
Client main:
import java.net.InetAddress;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int port;
System.out.println("Provide port at which you will communicate with the server");
port = scanner.nextInt();
try
{
ClientSocket socket1 = new ClientSocket(InetAddress.getByName("192.168.0.105"), port);
socket1.sendData();
}catch(Exception e)
{
System.out.println("Could not connect to the server.");
}
}
}
Server somehow stops its working when is about to accept the client connection, while client works fine and seem to be connected to the server.
In server side, once you accept a client connection, you should new a thread to process this connection:
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class MyServerSocket implements Runnable {
private ServerSocket serverSocket;
public MyServerSocket() throws Exception {
Random generator = new Random();
this.serverSocket = new ServerSocket(generator.nextInt(65000 - 60000) + 60000, 50, InetAddress.getByName("192.168.0.105"));
}
public InetAddress getSocketIPAddress() {
return this.serverSocket.getInetAddress();
}
public int getPort() {
return this.serverSocket.getLocalPort();
}
public void run() {
while (true) {
System.out.println("Running a thread");
try(Socket client = this.serverSocket.accept()) {
// new thread to process this client
new Thread(() -> {
try {
String data = null;
String clientAddress = client.getInetAddress().getHostName();
System.out.println("Connection from: " + clientAddress);
System.out.println("Here I am");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
String message = "";
while (true) {
if (!((data = in.readLine()) != null && data.compareToIgnoreCase("quit") != 0)) break;
message = ("\r\nMessage from " + clientAddress + ": " + data);
System.out.println(message);
out.write(message);
}
} catch (IOException e) {
System.out.println("Something went wrong");
}
}).start();
} catch (Exception e) {
System.out.println("Something went wrong");
}
}
}
}
Ok, somehow I solved that problem, but still I need to understand how does it work:
Accepting connection inside try block, without finally block (nor try with resources) so socket is opened all the time.
Modified main method so there is no threads or runnable objects at all in it. The whole process is done within the class:
Code:
public class Main
{
public static void main(String[] args)
{
try
{
MyServerSocket socket = new MyServerSocket();
System.out.println("Port number: " + socket.getPort() + " IP address: " + socket.getSocketIPAddress());
socket.run();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
If anyone could point me out mistakes that are still in this final version of code I'll be grateful.

Toggle between two network ports Java

I am trying to send a message from publisher file (sending on port 8000) which is received by Server (listening on port 5000 and 8000)and which forwards the message to the subscriber(listening on port 5000). The problem is that, communication between publisher and server is fine, however, I am not able to forward the message to the subscriber because the server is still listening to publisher and toggling to the subscriber port and forwarding the message. Any suggestion is appretiated
Publisher
package serverclient;
import java.net.*;
import java.io.*;
public class Publisher {
public static void main (String [] args) throws IOException{
Socket sock = new Socket("127.0.0.1",8000);
// reading from keyboard (keyRead object)
BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
// sending to client (pwrite object)
OutputStream ostream = sock.getOutputStream();
PrintWriter pwrite = new PrintWriter(ostream, true);
InputStream istream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
System.out.println("Start the chitchat, type and press Enter key");
String receiveMessage,sendMessage;
while(true)
{
sendMessage = keyRead.readLine(); // keyboard reading
pwrite.println(sendMessage); // sending to server
pwrite.flush(); // flush the data
if((receiveMessage = receiveRead.readLine()) != null) //receive from server
{
System.out.println(receiveMessage); // displaying at DOS prompt
}
else{
System.out.print("Null");
}
}
}
}
Subscriber
package serverclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
public class Subscriber {
public static void main (String [] args) throws IOException{
Socket sock = new Socket("127.0.0.1",5000);
// receiving from server ( receiveRead object)
InputStream istream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
System.out.println("Recive side");
System.out.print("Connection Status: " + sock.isConnected() + " " + sock.getPort());
String receiveMessage, sendMessage;
while(true)
{
System.out.print("Hey man " + receiveRead.readLine() + "\n");
if((receiveMessage = receiveRead.readLine()) != null) //receive from server
{
System.out.println(receiveMessage); // displaying at DOS prompt
break;
}
else{
System.out.print("Null");
}
}
}
}
Server
package serverclient;
import java.io.*;
import java.net.*;
public class Server extends Thread{
private Socket socket;
private int clientNumber;
public Server(Socket socket, int clientNumber){
this.socket = socket;
this.clientNumber = clientNumber;
if(socket.getLocalPort() == 5000)System.out.print("\nSubscriber "+ clientNumber +" is connected to the server");
if(socket.getLocalPort() == 8000)System.out.print("\nPublisher "+ clientNumber +" is connected to the server");
}
#Override
public void run(){
try {
BufferedReader dStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
System.out.print("\nSocket Address "+ socket.getLocalPort() + " " + socket.getPort());
while(true){
if ( socket.getInputStream().available() != 0 && socket.getLocalPort() == 8000 ){
synchronized(this){
String clMessage = dStream.readLine();
System.out.println(clMessage);
out.println("Hey the publisher has sent the message : " + clMessage);
}
}else if (socket.getInputStream().available() != 0 && socket.getLocalPort() == 5000 ){
out.println("Hey man I am so good");
}
}
} catch (IOException ex) {
System.out.print("\nError has been handled 1\n");
}finally{
try {
socket.close();
} catch (IOException ex) {
System.out.print("\nError has been handled 2\n");
}
}
}
public static void main(String [] args) throws IOException{
int subNumber = 0;
int pubNumber = 0;
ServerSocket servSockpub = new ServerSocket(8000);
ServerSocket servSocksub = new ServerSocket(5000);
try {
while (true) {
Server servpub = new Server(servSockpub.accept(),++pubNumber);
servpub.start();
System.out.print("\nThe server is running on listen port "+ servSockpub.getLocalPort());
Server servsub = new Server(servSocksub.accept(),++subNumber);
servsub.start();
System.out.print("\nThe server is running on listen port "+ servSocksub.getLocalPort());
}
} finally {
servSockpub.close();
servSocksub.close();
}
}
}
I see nothing wrong with the server ports (no duplicates/collisions).
But you have no code whatsoever that bridges data between the 2 sockets.
Basically, you should have 1 server that receives the 2 sockets and move data across in1-out2.
Careful too, in your code you can only connect a subscriber once the publisher has connected.

Handle java.net.SocketException: Socket closed when multithreading?

I'm doing a school project where we are supposed to create a simplefied Hotel booking system and then use it with a server/client communication.
Since I wanted to push the project a bit and do a multithreaded program, I've got a Socket Exception that I'm not sure how to handle. I've searched everywhere for an answer and I know that the exception occours because I'm trying to use a socket that has been closed. But from what I've read on Oracle-docs, their example is doing that as well.
So, is this actually Ok, just that I need to handle the exception? Cause my code runs fine, I just see the exceptions since I've put e.printStackTrace(); in my catch.
My Client class:
package client;
import java.io.*;
import java.net.Socket;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
Socket client = new Socket("localhost", 6066);
//System.out.println("Just connected to " + client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
LocalDate localDate = LocalDate.now();
String date = DateTimeFormatter.ofPattern("yyy/MM/dd").format(localDate);
System.out.println(in.readUTF());
System.out.print("Namn: ");
String name = sc.nextLine();
System.out.print("Ålder: ");
String age = sc.nextLine();
out.writeUTF(name);
out.writeUTF(age);
out.writeUTF(date);
System.out.println(in.readUTF());
client.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
And my Server class:
package server;
import java.io.IOException;
import java.net.*;
public class Server {
public static void main(String [] args) throws IOException {
int port = 6066;
ServerSocket server = new ServerSocket(port);
while(true) {
System.out.println("Listening for client..");
try {
Socket connectedClient = server.accept();
ClientHandle ch = new ClientHandle(connectedClient);
Thread t = new Thread((Runnable) ch);
t.start();
}catch (IOException e) {
}
}
}
}
And then my ClientHandle class which has the run() for the server-side:
package server;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.*;
import resources.*;
public class ClientHandle implements Runnable{
Socket connectedClient;
DataInputStream in;
DataOutputStream out;
public ClientHandle(Socket connectedClient) {
this.connectedClient = connectedClient;
try{
this.in = new DataInputStream(this.connectedClient.getInputStream());
this.out = new DataOutputStream(this.connectedClient.getOutputStream());
}catch(IOException ex) {
}
}
Hotel hotel = new Hotel();
Ticket yourTicket = new Ticket();
Server server = new Server();
#Override
public void run() {
while (true) {
try {
InetAddress host = InetAddress.getLocalHost();
System.out.println("Client " + host + " has connected.");
out.writeUTF("Välkommen till Hotel Gisslevik!\nVänligen fyll i nedan information för att slutföra din bokning.\n");
String yourName = in.readUTF();
String age = in.readUTF();
int yourAge = Integer.parseInt(age);
String date = in.readUTF();
yourTicket.setDate(date);
Person guest = new Person(yourName, yourAge);
hotel.setRooms();
Integer room = hotel.getRoom();
String rent = "J";
if (rent.indexOf("J") >= 0) {
yourTicket.setId(yourName);
if (hotel.checkIn(guest, room, yourTicket.getId(), yourTicket.getDate())) {
String yourId = yourTicket.getId();
out.writeUTF("\nDitt rum är nu bokat den " + date + ". \nBokningsnummer: " + yourId);
}
}
out.flush();
connectedClient.close();
}catch (EOFException e) {
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
}
If I just comment e.printStackTrace(); the exceptions doesn't show, but I would like to know how to handle them (if they should be handled). I've been searching the internet for days and checked out tutorials, but I don't find a proper answer to this.
I really appreciate any help you can provide.
Handle java.net.SocketException: Socket closed
Don't close the socket and then continue to use it.
when multithreading?
Irrelevant.
You have connectedClient.close() inside your while (true) loop. Solution: move it outside.

Server-Client chat program

I am writing a server-client chat program.
Here is my code
SERVER:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class HelloServer {
public final static int defaultPort = 2345;
public static void main(String[] args) {
int port = defaultPort;
try {
port = Integer.parseInt(args[0]);
} catch (Exception e) {
}
if (port <= 0 || port >= 65536) {
port = defaultPort;
}
try {
ServerSocket ss = new ServerSocket(port);
while (true) {
try {
Socket s = ss.accept();
String response = "Hello " + s.getInetAddress() + " on port " + s.getPort()
+ "\r\n";
response += "This is " + s.getLocalAddress() + " on port " + s.getLocalPort()
+ "\r\n";
OutputStream out = s.getOutputStream();
out.write(response.getBytes());
System.out.write(response.getBytes());
InputStream in = s.getInputStream();
System.out.println("from client");
int z = 0;
while ((z = in.read()) != -1) {
System.out.write(z);
}
} catch (IOException e) {
}
}
} catch (IOException e) {
System.err.println(e);
}
}
}
CLIENT:
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketGetINetAdd {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("192.xxx.x.xxx", 2345);
InetAddress inetAddress = socket.getInetAddress();
System.out.println("Connected to:: " + inetAddress.getHostName() + " Local address:: "
+ socket.getLocalAddress() + " Local Port:: " + socket.getLocalPort());
BufferedInputStream bfINPUT = new BufferedInputStream(socket.getInputStream());
int b = 0;
OutputStream os = System.out;
while ((b = bfINPUT.read()) != -1) {
os.write(b);
}
OutputStream osNew = socket.getOutputStream();
String s = "This Is The Client"; // data to be sent
osNew.write(s.getBytes());
os.write(s.getBytes());
}
I've connected them through my program.
But now I want to know How to send some data back to the server from client?
What would be the code for client(for sending data to server) and also the code for the server for showing the data received from the client on the console(server)?
P.S- I am a novice in network programming. Please do not criticize my coding style :P
Use server stream
OutputStream os = socket.getOutputStream();
instead of client console output stream
OutputStream os = System.out;
at client side to write back to server.
and at server side use client stream to read from client in the same manner.
InputStream in = s.getInputStream();
I have already posted a sample code on server-client communication. Read it for your learning.
You need threads. The client in this examples read the lines from the System.in and sends the line to the server. The server sends an echo.
In your real application you have to take a look of the encoding
Server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class HelloServer {
public final static int defaultPort = 2345;
public static void main(String[] args) {
int port = defaultPort;
try {
port = Integer.parseInt(args[0]);
} catch (Exception e) {
}
if (port <= 0 || port >= 65536) {
port = defaultPort;
}
try {
ServerSocket ss = new ServerSocket(port);
while (true) {
try {
Socket s = ss.accept();
new SocketThread(s).start();
} catch (IOException e) {
}
}
} catch (IOException e) {
System.err.println(e);
}
}
public static class SocketThread extends Thread {
private Socket s;
public SocketThread(Socket s) {
this.s = s;
}
#Override
public void run() {
try {
String response = "Hello " + s.getInetAddress() + " on port "
+ s.getPort() + "\r\n";
response += "This is " + s.getLocalAddress() + " on port "
+ s.getLocalPort() + "\r\n";
OutputStream out = s.getOutputStream();
out.write(response.getBytes());
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
while (true) {
String line = input.readLine();
System.out.println("IN: " + line);
s.getOutputStream().write(("ECHO " + line + "\n").getBytes());
s.getOutputStream().flush();
System.out.println(line);
}
} catch (IOException e) {
System.err.println(e);
}
}
}
}
Client
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketGetINetAdd {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("localhost", 2345);
InetAddress inetAddress = socket.getInetAddress();
System.out.println("Connected to:: " + inetAddress.getHostName() + " Local address:: " + socket.getLocalAddress() + " Local Port:: " + socket.getLocalPort());
new OutputThread(socket.getInputStream()).start();
InputStreamReader consoleReader = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(consoleReader);
while (true) {
String inline = in.readLine();
if (inline.equals("by")) {
break;
}
inline += "\n";
socket.getOutputStream().write(inline.getBytes());
socket.getOutputStream().flush();
}
}
public static class OutputThread extends Thread {
private InputStream inputstream;
public OutputThread(InputStream inputstream) {
this.inputstream = inputstream;
}
#Override
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(inputstream));
while (true) {
try {
String line = input.readLine();
System.out.println(line);
} catch (IOException exception) {
exception.printStackTrace();
break;
}
}
}
}
}

Categories