peer to peer communication - java - java

I need to create a program where a peer needs to communicate with other peer. I have vaguely created a structure but it does not work. I know I am making a mistake but not able to figure out the problem. I create a server socket as a thread and create a client socket thread which will talk to the server socket thread. after I enter a port, the program does nothing...
server.java
------------
class server
{
public static void main(String argv[]) throws Exception
{
//server socket
ServerSocket server = new ServerSocket(1001);
Socket client;
while(true)
{
client = server.accept();
Thread t = new Thread(new acceptconnection(client));
t.start();
}
}
}
class acceptconnection implements Runnable
{
BufferedReader inFromClient,inn;
DataOutputStream ds;
Socket clientsocket;
acceptconnection (Socket socket) throws IOException
{
this.clientsocket = socket;
inn = new BufferedReader (new InputStreamReader(System.in));
inFromClient =new BufferedReader(new
InputStreamReader(clientsocket.getInputStream()));
ds = new DataOutputStream(clientsocket.getOutputStream());
}
#Override
public void run ()
{
try
{
String clientSentence, inp;
while(( clientSentence = inFromClient.readLine())!=null)
{
System.out.println("message from remote socket #" +
clientsocket.getRemoteSocketAddress()+ clientSentence);
inp=inn.readLine();
ds.writeBytes(inp + "\n");
ds.flush();
}
}
}
}
client.java
------------
class client
{
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
Socket clientSocket = null;
// ss = new ServerSocket(10002);
clientSocket = new Socket("localhost", 1001);
BufferedReader inFromUser = new BufferedReader( new
InputStreamReader(System.in));
DataOutputStream outToServer = new
DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
System.out.println("Enter you name:");
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + "\n" );
System.out.println("Enter the port u want:");
sentence = inFromUser.readLine();
int serverport = Integer.parseInt(sentence);
Thread t = new Thread(new acceptconnection1(serverport));
t.start();
String msg;
clientSocket.close();
}
}
class acceptconnection1 implements Runnable {
BufferedReader inserver, inn;
DataOutputStream ds;
Socket socket, peersocket;
int serverport ;
Socket clientSocket = null;
acceptconnection1 (int serverport) throws IOException{
this.serverport = serverport;}
public void run () {
ServerSocket ss;
String cs,a;
try {
ss = new ServerSocket(serverport);
while(true)
{
peersocket =ss.accept();
Thread t = new Thread(new abc(peersocket) );
t.start();
}}}
class abc implements Runnable {
BufferedReader inn,inp;
DataOutputStream ds;
Socket peersocket;
public abc(Socket peersocket) throws IOException{
this.peersocket = peersocket;
inn = new BufferedReader (new InputStreamReader(System.in));
inp =new BufferedReader(new InputStreamReader(peersocket.getInputStream()));
ds = new DataOutputStream(peersocket.getOutputStream());
}
#Override
public void run()
{
String clientSentence;
Socket client = new Socket();
try {
while(( clientSentence = inp.readLine())!=null)
{
ds.writeBytes("wake up!");
//System.out.println("message=" + clientSentence);
}

Related

ObjectoutStram not set when trying to connect two client Socket to a server

I Have Class like below trying to connect two client socket to a server but when they get accepted by server I can only send data to the server through first socket (named s1 in code) and the second socket can do not send data to the server
public class Client_1 {
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
Socket s1 = new Socket("localhost", 8888);
Socket s2 = new Socket("localhost", 8888);
BufferedOutputStream bos1 = new BufferedOutputStream(s1.getOutputStream());
ObjectOutputStream oos1 = new ObjectOutputStream(bos1);
oos1.flush();
BufferedOutputStream bos2 = new BufferedOutputStream(s2.getOutputStream());
ObjectOutputStream oos2 = new ObjectOutputStream(bos2);
oos2.flush();
BufferedInputStream bis1 = new BufferedInputStream(s1.getInputStream());
ObjectInputStream ois1 = new ObjectInputStream(bis1);
BufferedInputStream bis2 = new BufferedInputStream(s2.getInputStream());
ObjectInputStream ois2 = new ObjectInputStream(bis2);
oos1.writeObject("a message from first client s1");
oos1.flush();
oos2.writeObject("a message from second client s2"); // sever does not receive this one
oos2.flush();
}
}
here is server code waiting for client
public class Main {
public static void main(String[] args) throws IOException {
WaitForClient();
}
public static void WaitForClient() throws IOException {
ServerSocket serverSocket = new ServerSocket(8888);
int i = 0;
while(true) {
Socket client = serverSocket.accept();
i++;
System.out.println(i + " client connected");
ClientThread clientThread = new ClientThread(client);
Thread thread = new Thread(clientThread);
thread.setDaemon(true);
thread.start();
}
}
and this is ClientThread who get info from socket
public class ClientThread implements Runnable {
Socket clientSocket;
ObjectInputStream oIStream;
ObjectOutputStream oOStream;
Object inputObject;
BufferedInputStream bIS;
BufferedOutputStream bOS;
public ClientThread(Socket clientSocket) {
this.clientSocket = clientSocket;
}
#Override
public void run() {
try {
bOS = new BufferedOutputStream(clientSocket.getOutputStream());
bIS = new BufferedInputStream(clientSocket.getInputStream());
oOStream = new ObjectOutputStream(bOS);
oOStream.flush();
oIStream = new ObjectInputStream(bIS);
while (clientSocket.isConnected()) {
if (bIS.available() > 0) {
inputObject = oIStream.readObject();
doService(inputObject);
System.out.println(inputObject.toString());
inputObject = null;
}
}
System.out.println("connection is closed!!!");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
System.out.println("socket exception" + e.getMessage());
}
}
}
and this is what printed to console
1 client connected
2 client connected
a message from first client s1 // input from the first socket but nothing from the second socket
This code should work,Are you getting any error in doService method?. In case any exception while loop will break and print statement will not be executed. Otherwise it should print data from both client

How do I send a Message to all Clients on a multithreaded Server?

I have written a simple multithreaded Server on which the two Clients can send Messages to the Server an the Server a Message to all the Clients at once. But I can't get it to work as intended.
I already tried it by putting a List of all PrintWriters in the Server class and then print the Message through each PrintWriter but this didn't work either.
public class Client
{
private static final String IP = "10.59.0.188";
private Socket clientSocket;
private PrintWriter toServer;
private BufferedReader fromServer;
private BufferedReader input;
private String serverMessage;
private String clientMessage;
private String name;
public static void main(String[] args) {
try {
new Client();
} catch (Exception e) {
System.err.println(e);
}
}
public Client() throws IOException {
input = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Name: ");
name = input.readLine();
openConnection();
toServer.println(name);
while (true) {
clientMessage = input.readLine();
toServer.println(clientMessage);
}
//closeConnection();
}
private void openConnection() throws IOException{
clientSocket = new Socket(IP, 6666);
toServer = new PrintWriter(clientSocket.getOutputStream(), true);
fromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}
}
public class Server {
private ServerSocket serverSocket;
private BufferedReader input;
private Vector<ClientProcess> processList;
private int clientCount = 0;
private String serverMessage;
public static void main(String[] args) {
try {
new Server();
} catch (Exception e) {
System.err.println(e);
}
}
public Server() throws IOException {
startServer();
while (clientCount < 2) {
waitForNewClient();
}
for (ClientProcess clientProcess : processList) {
clientProcess.start();
System.out.println("Clientprocess started");
}
}
private void startServer() throws IOException {
processList = new Vector<>();
input = new BufferedReader(new InputStreamReader(System.in));
serverSocket = new ServerSocket(6666);
System.out.println("Server online");
}
private void waitForNewClient() throws IOException {
System.out.println("Waitin' for new Client...");
Socket clientSocket = serverSocket.accept();
ClientProcess clientProcess = new ClientProcess(clientSocket);
processList.add(clientProcess);
clientCount++;
}
}
public class ClientProcess extends Thread {
private Socket clientSocket;
private PrintWriter toClient;
private BufferedReader fromClient;
private String clientMessage;
private String serverMessage;
private String name;
private BufferedReader input;
public ClientProcess(Socket clientSocket) {
this.clientSocket = clientSocket;
input = new BufferedReader(new InputStreamReader(System.in));
}
#Override
public void run() {
try {
openClientConnection();
name = fromClient.readLine();
do {
clientMessage = fromClient.readLine();
System.out.println(name + ": " + clientMessage);
} while (true);
//closeClientConnection();
} catch (IOException e) {
System.err.println(e);
}
}
private void openClientConnection() throws IOException {
toClient = new PrintWriter(clientSocket.getOutputStream());
fromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
serverMessage = "ServerMessageTest00";
toClient.println(serverMessage);
System.out.println("Client Connection Online");
}
}
In the ClientProcess you create a new PrintWriter.
From the javadoc:
Creates a new PrintWriter, without automatic line flushing, from anexisting OutputStream.
This means your toClient.println(...); is wrote to the server's output buffer but will not be send to the client because you miss the toClient.flush().

Client-to-Client with server intermediary

I am trying to implement Client to Client which passes through the server. Client1 sends a line to the server and server forwards it to all the other clients.
Can you point out my mistake. Nothing is printed on the other clients.
Server Code:
public class Server {
int port;
ServerSocket server=null;
Socket socket=null;
ExecutorService exec = null;
ArrayList clients = new ArrayList();
DataOutputStream dos=null;
public static void main(String[] args) throws IOException {
Server serverobj=new Server(2000);
serverobj.startServer();
}
Server(int port){
this.port=port;
exec = Executors.newFixedThreadPool(3);
}
public void startServer() throws IOException {
server=new ServerSocket(2000);
System.out.println("Server running");
while(true){
socket=server.accept();
dos = new DataOutputStream(socket.getOutputStream());
clients.add(dos);
ServerThread runnable= new ServerThread(socket,new ArrayList<>(clients),this);
exec.execute(runnable);
}
}
private static class ServerThread implements Runnable {
Server server=null;
Socket socket=null;
BufferedReader brin;
Iterator it=null;
Scanner sc=new Scanner(System.in);
String str;
ServerThread(Socket socket, ArrayList clients ,Server server ) throws IOException {
this.socket=socket;
this.server=server;
System.out.println("Connection successful with "+socket);
brin=new BufferedReader(new InputStreamReader(socket.getInputStream()));
it = clients.iterator();
}
#Override
public void run() {
try{
while ((str = brin.readLine()) != null) {
while (it.hasNext()) {
try{
DataOutputStream dost=(DataOutputStream) it.next();
dost.writeChars(str);
dost.flush();
}
catch(IOException ex){
System.out.println("Error 1 "+ex);
}
}
}
brin.close();
socket.close();
}
catch(IOException ex){
System.out.println("Error 2 "+ex);
}
}
}
}
Client 1 code:
public class Client1 {
public static void main(String args[]) throws IOException{
String str;
Socket socket=new Socket("127.0.0.1",2000);
PrintStream prout=new PrintStream(socket.getOutputStream());
BufferedReader bread=new BufferedReader(new InputStreamReader(System.in));
BufferedReader dis=new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(true){
System.out.println("Send to others:");
str=bread.readLine();
prout.println(str);
}
}
}
Other Clients:
public class Client2 {
public static void main(String args[]) throws IOException{
String str;
Socket socket=new Socket("127.0.0.1",2000);
BufferedReader dis=new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(true){
str=dis.readLine();
System.out.print("Message: "+str+"\n");
}
}
}
Please help.. I have been at it for 2 days...

Simple client server with loop messaging

I am trying to implement a simple client server program that will continuously exchange messages until client decides to stop. I found many tutorials on this topic, however I am struggling with implementing the loop correctly. The server processes the first request but does not process the others.
It is probably some silly mistake so please excuse me for asking such basic question - I am new to sockets. I would be glad for any help. I provide all the code (based on some example that I found):
Client:
public class Client {
public static void main(String argv[]) throws Exception {
talkWithServer();
}
private static void talkWithServer() throws UnknownHostException, IOException {
String sentence;
String serverResponse;
BufferedReader brClient = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 9000);
DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader brServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while(true) {
sentence = brClient.readLine();
out.writeBytes(sentence + '\n');
serverResponse = brServer.readLine();
System.out.println(serverResponse);
if (serverResponse.contains("<BYE>")) {
break;
}
}
clientSocket.close();
}
}
Server:
public class Server {
public static void main(String args[]) throws Exception {
String clientSentence;
ServerSocket welcomeSocket = new ServerSocket(9000);
Protocol protocol = new Protocol();
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(
connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
String response = protocol.processInput(clientSentence);
outToClient.writeBytes(response + '\n');
}
}
}
Protocol:
public class Protocol {
public String processInput(String theInput) {
String theOutput = "> " + theInput;
return theOutput;
}
}
I simplified the example for sake of easier debugging. Thanks for any tips!
My guess is line "Socket connectionSocket = welcomeSocket.accept();"
If I remember right, this will try to accept new client everytime, and since you are connecting just one, it will wait on that line forever in second iteration.
I suggest you paste that line before the while loop.
Try below
Socket connectionSocket = welcomeSocket.accept();
while (true) {
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(
connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
String response = protocol.processInput(clientSentence);
outToClient.writeBytes(response + '\n');
outToClient.flush();
}

Unable to send data from my server to client

I made a simple chat program where sending data from MyClient to MyServer is working, but when sending data from MyServer to MyClient is not working. So where I'm making mistake?
This is MyServer program:
import java.io.*;
import java.net.*;
public class MyServer{
ServerSocket ss;
Socket s;
DataInputStream din;
DataOutputStream dout;
public MyServer(){
try{
System.out.println("Server START......");
ss=new ServerSocket(9000);
s=ss.accept();
System.out.println("Client Connected.....");
din=new DataInputStream(s.getInputStream());
dout=new DataOutputStream(s.getOutputStream());
chat();
}
catch(Exception e){
System.out.println(e);}
}
public void chat()throws IOException{
String str=" ";
do{
str=din.readUTF();
System.out.println("Client Message: "+str);
dout.writeUTF("I have recieved ur message:"+str);
dout.flush();
}while(!str.equals("stop"));
}
public static void main(String arg[]){
new MyServer();}
}
This is MyClient program:
import java.io.*;
import java.net.*;
public class MyClient{
Socket s;
DataInputStream din;
DataOutputStream dout;
public MyClient(){
try{
s=new Socket("localhost",9000);
System.out.println(s);
din=new DataInputStream(s.getInputStream());
dout=new DataOutputStream(s.getOutputStream());
chat();
}catch(Exception e){
System.out.println(e);}
}
public void chat()throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s1;
do{
s1=br.readLine();
dout.writeUTF(s1);
dout.flush();
System.out.println("Server Message: "+din.readUTF());
}while(!s1.equals("stop"));
}
public static void main(String arg[]){
new MyClient();}
}
Actually you already do send an information from the server to the client with "I have received your message..."...
Anyway. If you want to send messages from the server to the client like a chat program your code should looks like this:
The Server part:
public class Server {
ServerSocket ss;
Socket s;
DataInputStream din;
DataOutputStream dout;
public Server() {
try {
System.out.println("Server START......");
ss = new ServerSocket(9000);
s = ss.accept();
System.out.println("Client Connected.....");
din = new DataInputStream(s.getInputStream());
dout = new DataOutputStream(s.getOutputStream());
chat();
} catch (Exception e) {
System.out.println(e);
}
}
public void chat() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s1;
do {
System.out.println("Client Message: " + din.readUTF());
s1=br.readLine();
dout.writeUTF(s1);
dout.flush();
} while (!s1.equals("stop"));
}
public static void main(String arg[]) {
new Server();
}
}
And for the client:
public class Client {
Socket s;
DataInputStream din;
DataOutputStream dout;
public Client() {
try {
s = new Socket("localhost", 9000);
System.out.println(s);
din = new DataInputStream(s.getInputStream());
dout = new DataOutputStream(s.getOutputStream());
chat();
} catch (Exception e) {
System.out.println(e);
}
}
public void chat() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s1;
do {
s1 = br.readLine();
dout.writeUTF(s1);
dout.flush();
System.out.println("Server Message: " + din.readUTF());
} while (!s1.equals("stop"));
}
public static void main(String arg[]) {
new Client();
}
}

Categories

Resources