Unable to send data from my server to client - java

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();
}
}

Related

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...

How to send ACK/NACK to server

Below is client and server program that I wrote. Now I am confused how to send ack/nack in my program.
I saw few answers on stackoverflow but i am still confused. Can you give an example of ACK/NACK in TCP protocol using java
Client:
public class Client {
public static void main(String args[]) {
try {
Socket client = new Socket("localhost", 2222);
PrintWriter pw = new PrintWriter(client.getOutputStream(), true);
Scanner input = new Scanner(System.in);
boolean a = true;
while (a) {
//receving
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.println(br.readLine());
if (input.equals("q")) {
a = false;
client.close();
}
pw.println("Client0: " + input.nextLine());
System.out.println(pw);
// System.out.println("Request sent successfully");
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
Server:
public class Server {
public static void main(String args[]) {
try {
ServerSocket ss = new ServerSocket(2222);
System.out.println("Waiting for client request");
Socket client = ss.accept();
System.out.println("Accepted connection request");
Scanner input = new Scanner(System.in);
while (true) {
// receving
InputStreamReader isr = new InputStreamReader(client.getInputStream());
BufferedReader br = new BufferedReader(isr);
String str = br.readLine();
// sending
PrintStream ps = new PrintStream(client.getOutputStream());
ps.println("Server1: " + input.nextLine());
System.out.println(ps);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
Thank you

Java Client Server chatting program

I got a code from the internet for a Client and Server to communicate in java. I modified it a bit, so that the server and client are able to chat to each other.
Initially my client sends a message to server, then server to client, then client to server and it goes on...(one cannot send more than one message continuously to the other). For this there is a basic code put in the while loop so that the conversation goes on 1 to 1. But as i put the while loop, the message from server is not received by client. If there is no while loop(which i have commented in the code here), then first the message is sent by client to server and then server to client and the program stops.
Please help me in making the chat go endlessly.
//SERVER
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private static Socket socket;
public static void main(String[] args)
{
try
{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
socket = serverSocket.accept();
System.out.println("Server Started and listening to the port 25000");
//while(true){
//Server is running always. This is done using this while(true) loop
//Reading the message from the client
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String number = br.readLine();
System.out.println("Received from client: "+number+"\n");
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
String s = bufferRead.readLine();
//Sending the response back to the client.
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(s);
bw.flush();
System.out.println("Sent (to " + socket + ") client: "+s+"\n");
//String abc = bufferRead.readLine();
//System.out.println("SAA");
//}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
socket.close();
}
catch(Exception e){}
}
}
}
//CLIENT
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
public class Client {
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);
//while(true){
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
String s = bufferRead.readLine();
String sendMessage = s + "\n";
bw.write(sendMessage);
bw.flush();
System.out.println("Sent to server: " +sendMessage+"\n");
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
System.out.println(socket);
String message = br.readLine();
System.out.println("Received from server: "+message+"\n");
//}
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
Server.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.*;
public class Server implements Runnable {
ServerSocket serversocket;
BufferedReader br1, br2;
PrintWriter pr1;
Socket socket;
Thread t1, t2;
String in="",out="";
public Server() {
try {
t1 = new Thread(this);
t2 = new Thread(this);
serversocket = new ServerSocket(5000);
System.out.println("Server is waiting. . . . ");
socket = serversocket.accept();
System.out.println("Client connected with Ip " + socket.getInetAddress().getHostAddress());
t1.start();;
t2.start();
} catch (Exception e) {
}
}
public void run() {
try {
if (Thread.currentThread() == t1) {
do {
br1 = new BufferedReader(new InputStreamReader(System.in));
pr1 = new PrintWriter(socket.getOutputStream(), true);
in = br1.readLine();
pr1.println(in);
} while (!in.equals("END"));
} else {
do {
br2 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = br2.readLine();
System.out.println("Client says : : : " + out);
} while (!out.equals("END"));
}
} catch (Exception e) {
}
}
public static void main(String[] args) {
new Server();
}
}
Client.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.*;
public class Client implements Runnable {
BufferedReader br1, br2;
PrintWriter pr1;
Socket socket;
Thread t1, t2;
String in = "", out = "";
public Client() {
try {
t1 = new Thread(this);
t2 = new Thread(this);
socket = new Socket("localhost", 5000);
t1.start();;
t2.start();
} catch (Exception e) {
}
}
public void run() {
try {
if (Thread.currentThread() == t2) {
do {
br1 = new BufferedReader(new InputStreamReader(System.in));
pr1 = new PrintWriter(socket.getOutputStream(), true);
in = br1.readLine();
pr1.println(in);
} while (!in.equals("END"));
} else {
do {
br2 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = br2.readLine();
System.out.println("Server says : : : " + out);
} while (!out.equals("END"));
}
} catch (Exception e) {
}
}
public static void main(String[] args) {
new Client();
}
}
//server.java
import java.io.*;
import java.net.*;
public class server {
public static void main(String []V){
try{
ServerSocket ss = new ServerSocket(1201);
Socket s = ss.accept();
DataInputStream Din = new DataInputStream(s.getInputStream());
DataOutputStream Dout = new DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String MsgIn="",MsgOut="";
while(!MsgIn.equals("end")){
MsgIn = Din.readUTF();
System.out.println(MsgIn);
MsgOut = br.readLine();
Dout.writeUTF(MsgOut);
Dout.flush();
}
s.close();
}catch(Exception e){
}
}
}
//clients.java
import java.io.*;
import java.net.*;
import javax.xml.crypto.Data;
public class clients {
public static void main(String []S){
try{
Socket s = new Socket("192.168.0.103",1201);//my pc's ip
//Socket s = new Socket("192.168.0.100",1201);
DataInputStream Din = new DataInputStream(s.getInputStream());
DataOutputStream Dout = new DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String MsgIn="",MsgOut="";
while(!MsgIn.equals("end")){
MsgOut = br.readLine();
Dout.writeUTF(MsgOut);
MsgIn = Din.readUTF();
System.out.println(MsgIn);
}
}catch(Exception e){
}
}
}
import java.io.*;
import java.net.*;
class serversvi1
{
public static void main(String svi[])throws IOException
{
try
{
ServerSocket servsock=new ServerSocket(5510);
DataInputStream dis=new DataInputStream(System.in);
System.out.println("enter the file name");
String fil=dis.readLine();
System.out.println(fil+" :is file transfer");
File myfile=new File(fil);
while(true)
{
Socket sock=servsock.accept();
byte[] mybytearray=new byte[(int)myfile.length()];
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(myfile));
bis.read(mybytearray,0,mybytearray.length);
OutputStream os=sock.getOutputStream();
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
}
}
catch(Exception saranvi)
{
System.out.print(saranvi);
}
}
}
import java.io.*;
import java.net.*;
class clientsvi1
{
public static void main(String svi[])throws IOException
{
try
{
Socket sock=new Socket("localhost",5510);
byte[] bytearray=new byte[1024];
InputStream is=sock.getInputStream();
DataInputStream dis=new DataInputStream(System.in);
System.out.println("enter the file name");
String fil=dis.readLine();
FileOutputStream fos=new FileOutputStream(fil);
BufferedOutputStream bos=new BufferedOutputStream(fos);
int bytesread=is.read(bytearray,0,bytearray.length);
bos.write(bytearray,0,bytesread);
System.out.println("out.txt file is received");
bos.close();
sock.close();
}
catch(Exception SVI)
{
System.out.print(SVI);
}
}
}

Why I can't connect two different laptops via WiFi?

This is a simple client-server program. It works fine when executed in a single computer. But, it doesn't work when executed in two different laptops connected using WiFi.
Here's the code:
Server:
public class Server
{
private static int port;
private ServerSocket serverSocket;
public void GreetingServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(20000);
while(true)
{
try
{
System.out.println("Waiting for client");
Socket server = serverSocket.accept();
System.out.println("Connected");
DataInputStream in =new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to ");
server.close();
}
catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}
catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String [] args)
{
port=9001;
try
{
Server s=new Server();
s.GreetingServer(port);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Client:
public class Client
{
private static String serverName;
public static void main(String [] args)
{
String sName = "192.168.xxxx.x";
int port = 9001;
try
{
System.out.println("Connecting to " + sName
+ " on port " + port);
Socket client = new Socket(sName, port);
System.out.println("Connected");
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from " + client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
}catch(IOException e)
{
}
}
}
What could be the problem? Please me..
Thanks in advance..

peer to peer communication - 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);
}

Categories

Resources