File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help me in this code!

 
Vu Trang
Greenhorn
Posts: 2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm a newbie in Java
I wrote a short code to run an application in java.net
I don't understand why client can't receive the result returned from server.
Can you help me?

Server:
import java.net.*;
import java.lang.*;
import java.io.*;

public class ServerReverse
{
public static void main(String[] args)
{

try
{
ServerSocket server = new ServerSocket(2266);

Socket client = server.accept();

System.out.println("The connection starts");

InputStreamReader reader = new InputStreamReader(client.getInputStream());
BufferedReader inStream = new BufferedReader(reader);
String str = inStream.readLine();
System.out.println("Received String from client : " +str);

int len = str.length();
char outChar[] = new char[len];
for (int i=0; i<len; i++)
outChar[len-i-1] = str.charAt(i);
String reversedStr = String.valueOf(outChar);

System.out.println("Reversed String : " +reversedStr);

DataOutputStream sentToClient = new DataOutputStream(client.getOutputStream());
for (int i=0; i<reversedStr.length(); i++)
sentToClient.write((byte)reversedStr.charAt(i));

client.close();
server.close();
}



catch (IOException e)
{
System.out.println("Has error when opening the connection");
}
}
}


Client :
import java.net.*;
import java.io.*;
import java.lang.*;

public class ClientReverse
{
public static void main(String[] args)
{
try
{
Socket client = new Socket("LocalHost",2266);

System.out.print("Nhap chuoi can xu ly gui den Server : ");
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader inStream = new BufferedReader(reader);
String sentStr = inStream.readLine();
System.out.println("Sent String : " +sentStr);

DataOutputStream outStr = new DataOutputStream(client.getOutputStream());
outStr.writeBytes(sentStr);

InputStreamReader reversedStr = new InputStreamReader(client.getInputStream());
BufferedReader stream = new BufferedReader(reversedStr);
String strEnd = stream.readLine();

System.out.println("Reversed String : " +strEnd);

outStr.close();
client.close();
}


catch (IOException e)
{
System.out.println(e);
}
}
}
 
Joe Ess
Bartender
Posts: 9214
9
Linux Mac OS X Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the JavaRanch, Vu.
Your problem is simple: You are using a BufferedReader to read lines but you aren't writing any line termination characters to the socket.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic