I have a server and a client. Server is capable of handling multiple request. Client opens a socket and sends a stream of bytes. While the server is processing, it is not behaving correctly. From the client I am sending the following lines
ADD this as your client
Title: Client1
for 5 different clients
I am using the string builder to build the formatted string as above.
for (i=0; i<6; i++)
{
Socket socket = new Socket(host, port);
StringBuilder sb = new StringBuilder();
sb.append("ADD this as your client ");
sb.append("\r\n");
sb.append("Title: Client");
sb.append(i);
sb.append("\r\n");
String ToSend = sb.toString();
/// New Additions
byte[] byteArray = ToSend.getBytes();
OutputStream os = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeInt(byteArray.length);
dos.write(byteArray,0,byteArray.length);
socket.close();
}
In the server I am reading this like this.
public static void main(String[] args) {
Sampleserver file_rec = new Sampleserver();
try {
ServerSocket listener = new ServerSocket(port);
while (true) {
file_rec.socket = listener.accept();
new Thread(file_rec).start();
}
}
catch (java.lang.Exception ex) {
ex.printStackTrace(System.out);
}
}
public void run() {
try {
InputStream is = socket.getInputStream();
DataInputStream dis = new DataInputStream(is);
int length = dis.readInt();
System.out.println("Length value is " + length);
byte[] mybytearray = new byte[length];
int bytesRead = is.read(mybytearray, 0, length);
String s = new String(mybytearray, 0, length);
System.out.println(s);
if (s.contains("ADD"))
{
System.out.println("Inside ADD. ");
}
else
{
System.out.println("Default ");
}
}
catch (java.lang.Exception ex) {
ex.printStackTrace(System.out);
}
}
But everytime in the server I am getting weird output. I think I am not handling either the bytearray properly or handling it wrongly in the server while processing it in threaded environment (in the run method). Can you please tell me where i am going wrong.