Below is my server program,
import java.io.*;
import java.net.*;
class TwoWayServer
{
public static void main(String argv[]) throws Exception
{
ServerSocket server_socket = new ServerSocket(1234);
while(true)
{
Socket listen_socket = server_socket.accept();
BufferedReader client_input = new BufferedReader(new InputStreamReader(listen_socket.getInputStream()));
DataOutputStream dos = new DataOutputStream(listen_socket.getOutputStream());
String client_str = client_input.readLine();
System.out.println(client_str);
String st=client_str.toUpperCase();
dos.writeBytes(st);
}
}
}
And my client program is as follows,
import java.io.*;
import java.net.*;
class TwoWayClient
{
public static void main(String argv[]) throws Exception
{
BufferedReader user_input = new BufferedReader( new InputStreamReader(System.in));
Socket socket = new Socket("localhost", 1234);
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
BufferedReader server_response = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String client_str = user_input.readLine();
dos.writeBytes(client_str + '\n');
String response = server_response.readLine();
System.out.println("FROM SERVER: " + response);
socket.close();
}
}
Here, if I give a string from the clientside then the server return the capitalized form of the string. But the problem is that once I have provided the string, I'm not getting any response from the server.
Kindly help.
The problem is in the server in not writing the bytes to the server with a newline character try replacing dos.writeBytes(st);
with
dos.writeBytes(st + "\n");
You may try these modifications to your code.
Server:
import java.io.*;
import java.net.*;
class TwoWayServer
{
public static void main(String argv[]) throws Exception
{
ServerSocket server_socket = new ServerSocket(1234);
while(true)
{
Socket listen_socket = server_socket.accept();
BufferedReader client_input = new BufferedReader(new InputStreamReader(listen_socket.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(listen_socket.getOutputStream()));
String client_str = client_input.readLine();
System.out.println(client_str);
String st=client_str.toUpperCase();
bw.write(st + '\n');
bw.flush();
}
}
}
Client:
import java.io.*;
import java.net.*;
class TwoWayClient
{
public static void main(String argv[]) throws Exception
{
BufferedReader user_input = new BufferedReader( new InputStreamReader(System.in));
Socket socket = new Socket("localhost", 1234);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
BufferedReader server_response = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String client_str = user_input.readLine();
bw.write(client_str + '\n');
bw.flush();
String response = server_response.readLine();
System.out.println("FROM SERVER: " + response);
socket.close();
}
}
Related
I was learning JAVA networking API and simple TCP server-client communication.
I have written the following two classes for client and server.
The issue is that my client is not responding i.e. the program is not terminating and it doesn't output anything .. Can anyone see where I am going wrong?
Client:
import java.io.*;
import java.net.*;
public class client {
public void go() {
try {
Socket s = new Socket("127.0.0.1",2323);
InputStreamReader streamReader = new InputStreamReader(s.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
String reading = reader.readLine();
PrintWriter write = new PrintWriter(s.getOutputStream());
write.print("mynameistom");
System.out.println(reading);
reader.close();
writeToServer.close();
} catch(IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
Client client = new Client;
client.go();
}
}
Server:
package TCP;
import java.io.*;
import java.net.*;
public class Server {
public void go() {
try {
ServerSocket serverSock = new ServerSocket(2323);
Socket socket = serverSock.accept();
InputStreamReader streamReader = new InputStreamReader(socket.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
String messsage = reader.readLine();
PrintWriter writer = new PrintWriter(socket.getOutputStream())
writer.println(message);
writer.close();
System.out.println(message);
} catch(IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
Server server = new Server();
server.go();
}
}
The obvious thing is that the client isn't flushing, and is missing the new line.
PrintWriter writeToServer = new PrintWriter(s.getOutputStream());
writeToServer.print("network");
Should be either
PrintWriter writeToServer = new PrintWriter(s.getOutputStream(), true);
writeToServer.println("network");
or
PrintWriter writeToServer = new PrintWriter(s.getOutputStream());
writeToServer.println("network");
writeToServer.flush();
I have made a socket in Java.
This socket connects with a server.
When I start my program, the server sends a message that my socket is connected with the AEOS.
When I try to login to the server for sending some commands, then the server responds again with: status connected to AEOS version
This is not the message that I expect, normally my server must send a "response true".
Can you help me?
Thanks.
import java.io.*;
import java.net.*;
class TCPClient {
public static void main(String argv[]) throws Exception {
while(true) {
String sentence;
String modifiedSentence;
Socket clientSocket = new Socket("127.0.0.1", 1201);
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
}
output socket
Why don't you try to read everything that server had sent? Also, need to open a new Socket every-time? Depends on your implementation. Try this:
public static void main(String[] args) {
Socket clientSocket = null;
try {
clientSocket = new Socket("127.0.0.1", 1201);
BufferedReader inFromUser = new BufferedReader(
new InputStreamReader(System.in));
DataOutputStream outToServer = new DataOutputStream(
clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
String initialMessageFromServer = null;
while ((initialMessageFromServer = inFromServer
.readLine()) != null) {
System.out.println(initialMessageFromServer);
}
while (true) {
String sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
StringBuilder modifiedSentence = new StringBuilder();
String responseFromServer = null;
while ((responseFromServer = inFromServer.readLine()) != null) {
modifiedSentence.append(responseFromServer);
modifiedSentence.append('\n');
}
System.out
.println("FROM SERVER: " + modifiedSentence.toString());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (clientSocket != null) {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I am trying to write a program that allows the user to send a message to a server and receive a modified version of that message. For some reason, the flow of the program stops on a certain line below, which I have pointed out. Can anybody explain why this isn't working? Thanks.
Server Side
import java.net.*;
import java.io.*;
public class Server{
public final static int port = 1025;
public static void main (String[] args){
ServerSocket serverSocket;
Socket client;
PrintWriter output;
try{
serverSocket = new ServerSocket(port);
try{
while(true){
client = serverSocket.accept();
InputStream is = client.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from client is " + message);
String returnMessage = message + message;
OutputStream os = client.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Message sent to the client is " + returnMessage);
bw.flush();
}
} catch(IOException e){
serverSocket.close();
System.err.println(e);
}
} catch(IOException e){
System.err.println(e);
}
}
}
Client Side
import java.util.Scanner;
import java.net.*;
import java.io.*;
class Client{
public void getService(String destination, int port){
try{
while(true)
{
Scanner in = new Scanner(System.in);
System.out.println("Send a message to the server: ");
String message = in.nextLine();
Socket server = new Socket(destination, port);
OutputStream os = server.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String sendMessage = message + "\n";
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+ sendMessage);
InputStream is = server.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message2 = br.readLine(); // I have determined that the program's flow proceeds no further than this line
System.out.println("Message received from the server : " + message2);
}
} catch(IOException e){
e.printStackTrace();
}
}
public static void main(String[] args){
String serverAddress = args[0];
System.out.println(serverAddress);
Client client = new Client();
client.getService(serverAddress, 1025);
}
}
The server uses a BufferedReader, whose readLine method requires an end of line delimiter, but the Client is not sending it - rather, it reads the line (with end of line delimiter stripped) and attempts to echo this message. Append a new line character to the data sent by the client so that the readLine method of the Server does not block while waiting for the line:
String returnMessage = message + message + "\n";
I am writing a client-server program in java using TCP/IP. For the purpose, I wrote the following codes:
serversock.java:
import java.net.*;
import java.io.*;
public class serversock {
public static void main(String[] args) throws IOException
{
ServerSocket sersock = null;
try
{
sersock = new ServerSocket(10007);
}
catch (IOException e)
{
System.out.println("Can't listen to port 10007");
System.exit(1);
}
Socket clientSocket = null;
System.out.println("Waiting for connection....");
try
{
clientSocket = sersock.accept();
}
catch ( IOException ie)
{
System.out.println("Accept failed..");
System.exit(1);
}
System.out.println("Conncetion is established successfully..");
System.out.println("Waiting for input from client...");
PrintWriter output = new PrintWriter(clientSocket.getOutputStream());
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine = input.readLine();
while ( inputLine != null)
{
output.println(inputLine);
System.out.println("Server: " + inputLine);
inputLine = input.readLine();
}
input.close();
clientSocket.close();
sersock.close();
}
}
clientsock.java:
import java.util.*;
import java.io.*;
import java.net.*;
public class clientsock
{
public static void main(String[] args) throws IOException
{
Socket sock = new Socket("localhost",10007);
// Scanner scan = new Scanner(System.in);
PrintWriter output = new PrintWriter(sock.getOutputStream(),true);
BufferedReader input = new BufferedReader( new InputStreamReader(sock.getInputStream()));
String line = null;
BufferedReader stdInput = new BufferedReader( new InputStreamReader(System.in));
System.out.println("Enter data to send to server: ");
line = stdInput.readLine();
while ( (line) != "bye")
{
output.println(line.getBytes());
line = stdInput.readLine();
System.out.println("Server sends: " + input.read());
}
sock.close();
}
}
Now on running the programs I got the following output:
server:
shahjahan#shahjahan-AOD270:~/Documents/java$ java serversock
Waiting for connection....
Conncetion is established successfully..
Waiting for input from client...
Server: [B#4e25154f
shahjahan#shahjahan-AOD270:~/Documents/java$
client:
shahjahan#shahjahan-AOD270:~/Documents/java$ java clientsock
Enter data to send to server:
qwe
sdf
^Cshahjahan#shahjahan-AOD270:~/Documents/java$
The server is recieving different symbols, and client receives nothing. Please help me to solve it.
In the client replace:
output.println(line.getBytes());
with
output.println(line);
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);
}
}
}