I have a Server-Client program where I send a small messsage to the client using JLabel. When that message is recieved from server that particular client must send a response immediately. But it is not sending any message . Can somebody look at my code and tell me where my mistake is?
//SERVER
void connect_clients()
{
try {
ServerSocket listener = new ServerSocket(7700);
jButton1.setText("Server Running!");
jButton1.setEnabled(false);
while (true) {
socket = listener.accept();
socketList.add(socket);
//socketList.add(listener.accept());
BufferedReader ed = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String tmp = ed.readLine();
System.out.print("I Recieved :"+tmp);
}
}
catch(IOException ex)
{
JOptionPane.showMessageDialog(null,ex);
}
}
//CLIENT
void connect_server() throws IOException
{
try {
// TODO code application logic here
String serverAddress = JOptionPane.showInputDialog(
"Enter IP Address of a machine that is\n" +
"running the date service on port 9090:");
s = new Socket(serverAddress, 7700);
while(true){
BufferedReader input =
new BufferedReader(new InputStreamReader(s.getInputStream()));
String answer = input.readLine();
System.out.println(answer);
if(answer != null)
{
PrintStream pr = new PrintStream(s.getOutputStream());
InputStreamReader rd = new InputStreamReader(System.in);
BufferedReader ed = new BufferedReader(rd);
String temp = ed.readLine();
pr.println(temp);
JOptionPane.showMessageDialog(null,"Answer is not null"); //THIS WORKS
}
}
}
catch (ConnectException e) {
JOptionPane.showMessageDialog(null, e);
}
catch (SocketException e) {
JOptionPane.showMessageDialog(null, e);
}
}
Some points that you missed in your implementation:
the streams and sockets are never closed
in the client i do not see the point of the endless loop
the client should initialize the communication by sending a message via output stream (not to try to read first)
For a simple example the steps should be:
Start sever to listen and once a connection is established to read the message (you did)
The client should sent a message via output stream and close the steams and the socket
The severs should close the streams and the sockect for the established connection
Example:
//Server
socket = listener.accept();
BufferedReader ed = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter pr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream());
String tmp = ed.readLine();
System.out.print("I Recieved :"+tmp);
String msg = "Message received";
pr.write(msg,0,msg.length());
pr.newLine();
ed.close();
pr.close();
socket.close();
//Client
BufferedWriter pr = new BufferedWriter(new OutputStreamWriter(s.getOutputStream());
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String sendMessage = "Send Message";
pr.write(msg,0,msg.length());
pr.newLine();
String answer = input.readLine();
System.out.println(answer);
JOptionPane.showMessageDialog(null,"Answer is not null");
input.close();
pr.close();
s.close();
UPDATE
reading from input stream continuously:
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line;
while((line=input.readLine())!=null){
//do something with line
}
I will suggest a simple approach where server is sending the hi msg to client.
For server:
//Server
ServerSocket ss=new ServerSocket(3554);
socket = ss.accept();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getOutputStream()));
String msg ="Hi from server"
bw.write(msg);
String msgFromClient=br.readLine();
System.out.println(msgFromClient);
bw.close();
socket.close();
For Client:
//Client
Socket socket=new Socket("localhost",3554)
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String received = input.readLine();
System.out.println(received);
bw.write("Client recieve :"+received);
br.close();
bw.close();
socket.close();
Related
The client sends data (string) to the server, and the server must read it, but in my case the server didn't read the data (value) that the client sent, and I didn't know where is the problem exactly, because normally the steps to read data are all correct in the server side
Client side:
Socket socket = new Socket(address, authenticationServerPort);
username = username + "\n"; // to send username through socket without
String h=getUserInput();
// waiting
// Send the message to the server
// send public key
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
System.out.println(h);
bw.write(h);
bw.flush();
System.out.println("Message sent to the Authentication server : "+ h);
Server side:
Socket clientSocket = null;
try {
System.out.println("Server Running");
int serverPort = 8029; // the server port we are using
ServerSocket listenSocket = new ServerSocket(serverPort);
List<BlockChain> resultList = new ArrayList<BlockChain>();
while (true) {
clientSocket = listenSocket.accept();
InputStream is = clientSocket.getInputStream();
System.out.println(is);
InputStreamReader isr = new InputStreamReader(is);
System.out.println(isr);
BufferedReader br = new BufferedReader(isr);
String request = br.readLine();
System.out.println("the msg receving from client is : "+request);
PrintWriter out;
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())));
if (clientSocket != null) {
clientSocket.close();
}
}
catch (Exception e) {
e.printStackTrace();// TODO: handle exception
}
}
Someone tell me where is the problem exactly.
I am new to socket programming. I have to write a program where client accepts filename from a user and sends it to the server. The server reads corresponding file and sends its content back to client. Now my problem is server program freezes on 'String file = br.readLine()'. When I terminate my client program, further lines of server code get executed. If I comment out while loop at the end of my client code, server code works perfectly fine(it prints data to standard output). Can you tell what could be wrong with my code?
Server Code:
public class SocketServer {
public static void main(String[] args) throws Exception{
System.out.println("Server is started.");
ServerSocket ss = new ServerSocket(9999);
System.out.println("Server is waiting for a client.");
Socket server = ss.accept();
System.out.println("Client is connected.");
BufferedReader br = new BufferedReader(new InputStreamReader(server.getInputStream()));
String file = br.readLine();
System.out.println("Requested file is: " + file);
OutputStreamWriter os = new OutputStreamWriter(server.getOutputStream());
PrintWriter writer = new PrintWriter(os);
BufferedReader fr = new BufferedReader(new FileReader(file));
String line;
while((line = fr.readLine()) != null) {
writer.write(line);
writer.flush();
System.out.println(line);
}
}
}
Client Code:
public class SocketClient {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
Socket client = new Socket("localhost", 9999);
OutputStreamWriter os = new OutputStreamWriter(client.getOutputStream());
PrintWriter writer = new PrintWriter(os);
System.out.print("Enter filename: ");
String file = in.nextLine();
writer.write(file);
writer.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.println("Content of " + file + ":");
String str;
while((str = br.readLine()) != null) {
System.out.print(str);
}
System.out.println("File transfer is complete.");
}
}
br.readLine(); will wait for input till it finds a new-line .
writer.write(file); You are writing file name without a new-line.
So in order to make it work either write a newline char at client or read it char by char at server.
Hope this helps.
I'm testing around with client-server communication.
I have a server that should receive messages and print them, and send messages that it gets from System.in using a Socket. The client reads messages from the Socket, and sends back some messages. But for some reason both the server and the client get locked when checking if there is a message from the other end (at readLine()).
This client:
public void run() {
try {
Log.i("DataManager", "Trying to connect to server");
socket.connect(new InetSocketAddress(ADDRESS, PORT), 3000);
Log.i("DataManager", "Connected to: " + socket.getInetAddress());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true); //autoflush
String inputLine;
while (socket.isConnected()) {
if ((inputLine = in.readLine()).isEmpty()){
Log.i("DataManager", "Server says: " + inputLine);
}
synchronized (outcoming){
if (!outcoming.isEmpty()){
for (int i = 0; i < outcoming.size(); i++){
out.println(outcoming.get(i));
outcoming.remove(i);
}
}
}
}
}
...
}//
The Server:
ServerSocket listener = new ServerSocket(PORT);
try {
Socket socket;
socket = listener.accept(); //waits for connection
System.out.println("Client connected: " + socket.getInetAddress());
BufferedReader sysRead = new BufferedReader(new InputStreamReader(System.in));
BufferedReader clientIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true); //autoflush
String inputLine;
out.println("Hello, you are connected to server" + listener.getInetAddress());
while (true){
if ((inputLine = clientIn.readLine()).isEmpty()){
System.out.println("Client says: " + inputLine);
}
String line = sysRead.readLine();
if (line.equals("stop")){
break;
} else {
out.println(line);
}
}
socket.close();
}
I tried solving this by encasing the readLine statements with if(in.ready()) but it didn't help at all. I've been looking around on google and found that this is caused by the fact that readLine() looks for eof, and the stream from the socket only ends when the socket is disconnected. I have no idea how to get around this problem other that writing some kind of protocol where i end my messages with a specific sequence. Is there a better way around this problem?
I wrote a simple socket tutorial about sending/receive messages between client and server. I used DataOutputStream to write the string in stream but server couldn't read it if I used BufferedReader
If I use PrintWriter to write(client side), it works.
What's wrong here? Tks so much.
1. Client:
client = new Socket("localhost", 1982);
DataOutputStream opStr = new DataOutputStream(client.getOutputStream());
//pw = new PrintWriter(client.getOutputStream(), true);
//pw.println("Hello, is there anybody out there?");// Can be read by BufferedReader
opStr.writeUTF("Hello, anyone there?");
opStr.flush();// BufferedReader can't read it
2. Server:
openServer();// port 1982
while(true) {
Socket clientSocket = null;
// listen to connection.
clientSocket = echoServer.accept();
DataInputStream inStr = new DataInputStream(
clientSocket.getInputStream());
//System.out.println("M1: Got msg " + inStr.readUTF());// It showed the content
BufferedReader bfReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("got Messages: ");
String strLine = "";
// Don't show anything
while ((strLine = bfReader.readLine()) != null) {
System.out.println(strLine);
}
}
You can't. If you use writeUTF() at one end, you have to use readUTF() at the other end.
You just have to decide which API you're going to use, instead of trying to mix and match them.
You want to read the files as either text e.g. BufferedReader OR binary e.g. DataInputStream. So you can't use both.
Server.java
public class Server
{
public static void main(String[] args)
{
DataInputStream inStr = null;
String str;
openServer();// port 1982
while(true)
{
Socket clientSocket = null;
// listen to connection.
clientSocket = echoServer.accept();
try
{
inStr = new DataInputStream(clientSocket.getInputStream());
str = inStr.readUTF();
System.out.print((String) str);
System.out.flush();
}
catch (IOException io)
{
System.err.println("I/O error occurred: " + io);
}
catch (Throwable anything)
{
System.err.println("Exception caught !: " + anything);
}
finally
{
if (inStr != null)
{
try
{
inStr.close();
}
catch (IOException io)
{
System.err.println("I/O error occurred: " + io);
}
}
}
}
}
}
So I am trying to have a sever sit and listen waiting for a connection from a client. The client sends over some string and the sever does some action based on whats received. Now what I would like to happen is the client sends over some command asking for data back and have the server get what it needs to and send the string back.
Not a big deal right? Well for some reason I can't get it working, my best guess is that its not closing the socket properly. I can't figure out why it wouldn't or what I am doing wrong.
Client
String data = "";
DataOutputStream outToServer = null;
BufferedReader input;
try {
outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes("GETDATA");
outToServer.flush();
input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
data = input.readLine();
Log.d("ANSWER: ", data);
input.close();
} catch (IOException e) {
Log.d("Error: ", e.toString());
}
Server
ServerSocket listeningSocket = new ServerSocket(9008);
BufferedReader fromClient ;
PrintStream os;
while(true) {
Socket clientSocket = listeningSocket.accept();
ServerConnection clientConnection = new ServerConnection(clientSocket);
os = new PrintStream(clientSocket.getOutputStream());
fromClient= new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
if(fromClient.readLine().equals("GETDATA")){
os.println("DATA");
os.flush();
clientSocket.wait();
clientSocket.close();
}
else{
clientConnection.run();
}
}
Any ideas?
here is your error
outToServer.writeBytes("GETDATA");
the right code is
outToServer.writeBytes("GETDATA\n");
as your using readline you should send a full line with line break