I've sent a string and images from Java Android to a C# server. But I'm having a problem with the integer array.
Is it a good logic to use dataOutputStream.writeByte(Array[i]) inside a for loop (Client side)?
I've tested with a small array of 6 elements only. In the server, the array elements are received but not the same numbers as in client array. Why is that?
OUTPUT:
client array : (1,3333,50,6,7,8}
server array : {37, 37, 9, 45, 18, 18}!!
Client Android:
public void ConnectToServer()
{
//generate array with random numbers
int[] array = {1,333,5,60,7,8};
try {
//Connect to socket
Socket socket = new Socket(HOST, PORT);
DataOutputStream outToServer = new DataOutputStream(socket.getOutputStream());
for(int i=0; i< 6; i++)
{ outToServer.writeByte(array[i]);}
outToServer.flush();
socket.shutdownOutput();
Log.e("MESSAGE", "array sent Successfully");
//receive msg from (server)
BufferedReader r = new BufferedReader(new InputStreamReader(socket.getInputStream())); //for reading response from server
recievedMsg = r.readLine();
//clean
r.close();
socket.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
Server:
static void Main(string[] args)
{
try
{
IPAddress ipAdress = IPAddress.Parse("192.168.10.3");client
TcpListener listener = new TcpListener(ipAdress, 4003);
listener.Start();
Console.WriteLine("Server Waiting for connections...");
Socket s = listener.AcceptSocket();
// When accepted
NetworkStream nstm = new NetworkStream(s);
BinaryReader reader = new BinaryReader(nstm);
byte result;
int number;
for (int i = 0; i < 6; i++)
{ result = reader.ReadByte();
number = Convert.ToInt32(result);
Console.WriteLine(number.ToString() + "---"+ i);
}
//send the response to client
Byte[] sendData = Encoding.ASCII.GetBytes("received !");
nstm.Write(sendData, 0, sendData.Length);
//Clean up
s.Close();
listener.Stop();
}
catch (Exception e)
{
Console.WriteLine("Error.....CL1 " + e.Message + e.StackTrace);
}
}
java use big endian, and c# use little endian.
Related
This question already has an answer here:
Java TCP server cannot receive message from more than one client
(1 answer)
Closed 5 years ago.
[Edit: This post has been marked as duplicate without reviewing properly. The two posts address completely different problem which the reviewer did not take time to carefully read.]
The server will connect to three instances of client. The server has three threads to receive requests from these three clients. Each of the three instances of client will have a ServerThread (the server requests for file or file list from this thread) and a UserThread (it will take user input and communicated with the server and receive file/file list depending on the user input).
Let's say client_0 wants a file that is in possession of client_1. When UserThread of client_0 requests the server for the file, the server communicates with ServerThread of client_1 and ServerThread of client_1 sends the byteArray of the file to the server. The server then sends the byteArray back to the UserThread of client_0 and client_0 then saves the byteArray as a file.
I am using the same type of code for the server to receive the bytearray from client_1 and for client_0 to receive the byteArray from the server. The server's code works perfectly everytime and receives the byteArrayperfectly but in client_0, the loop that receives the byteArray gets stuck at the last part of the file although the same type of loop is working perfectly in server. The variable position holds how much of the byteArray has been received and it doesn't reach the FILE_SIZE in the client_0 but does so in server without any problem. The System.out.println() statements confirm this.
In addition, this problem in client_0 is happening 90% of the time. In the other 10%, the loop in client_0 works just like it is supposed to! Why is this happening?
The codes are long but if anyone manages to go through and give some suggestion, it will be a great help.
Server:
package server;
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception {
String[] id={"cp 1","cp 2","cp 3"}, pass={"123","456","789"};
ServerSocket welcome = new ServerSocket(6000), tmpSocket;
Socket STsocket, UTsocket;
int startSTport = 6001;
int startUTport = 6011;
// for ServerThread of client
BufferedReader STmsgFrom[] = new BufferedReader[3];
PrintWriter STmsgTo[] = new PrintWriter[3];
DataInputStream[] STfileFrom = new DataInputStream[3];
// for UserThread of client
BufferedReader UTmsgFrom[] = new BufferedReader[3];
PrintWriter UTmsgTo[] = new PrintWriter[3];
DataOutputStream[] UTfileTo = new DataOutputStream[3];
for(int i=0; i<3; i++) {
// connecting initially
System.out.println("Waiting for client "+i);
Socket client = welcome.accept();
PrintWriter send = new PrintWriter(client.getOutputStream(),true);
BufferedReader receive = new BufferedReader(new InputStreamReader(client.getInputStream()));
// sending serial number
send.println(Integer.toString(i));
// sending ports for thread sockets
send.println(Integer.toString(startSTport+i));
send.println(Integer.toString(startUTport+i));
// accepting sockets
tmpSocket = new ServerSocket(startSTport+i);
STsocket = tmpSocket.accept();
tmpSocket = new ServerSocket(startUTport+i);
UTsocket = tmpSocket.accept();
// creating communications
STmsgFrom[i] = new BufferedReader(new InputStreamReader(STsocket.getInputStream()));
STmsgTo[i] = new PrintWriter(STsocket.getOutputStream(),true);
STfileFrom[i] = new DataInputStream(STsocket.getInputStream());
UTmsgFrom[i] = new BufferedReader(new InputStreamReader(UTsocket.getInputStream()));
UTmsgTo[i] = new PrintWriter(UTsocket.getOutputStream(),true);
UTfileTo[i] = new DataOutputStream(UTsocket.getOutputStream());
System.out.println("Connected client "+i);
}
ClientThread ct0 = new ClientThread(0,STmsgFrom,STmsgTo,STfileFrom,UTmsgFrom,UTmsgTo,UTfileTo);
ClientThread ct1 = new ClientThread(1,STmsgFrom,STmsgTo,STfileFrom,UTmsgFrom,UTmsgTo,UTfileTo);
ClientThread ct2 = new ClientThread(2,STmsgFrom,STmsgTo,STfileFrom,UTmsgFrom,UTmsgTo,UTfileTo);
ct0.start();
ct1.start();
ct2.start();
System.out.println("Server Stup Complete!");
}
}
class ClientThread extends Thread {
String msg;
int cid;
BufferedReader[] STmsgFrom;
PrintWriter[] STmsgTo;
DataInputStream[] STfileFrom;
BufferedReader[] UTmsgFrom;
PrintWriter[] UTmsgTo;
DataOutputStream[] UTfileTo;
public ClientThread(int cid,BufferedReader[] STmsgFrom,PrintWriter[] STmsgTo,DataInputStream[] STfileFrom,BufferedReader[] UTmsgFrom,PrintWriter[] UTmsgTo,DataOutputStream[] UTfileTo) {
this.cid=cid;
this.STmsgFrom=STmsgFrom;
this.STmsgTo=STmsgTo;
this.STfileFrom = STfileFrom;
this.UTmsgFrom=UTmsgFrom;
this.UTmsgTo=UTmsgTo;
this.UTfileTo = UTfileTo;
}
#Override
public void run() {
while(true) {
try {
// receiving request from receiver UserThread
msg = UTmsgFrom[cid].readLine();
if(msg.equals("get list")) { // receiver requested for file list
System.out.println("Request from "+cid+": "+msg);
for(int i=0; i<3; i++) {
if(i==cid) continue;
// sending request to sender ServerThread
STmsgTo[i].println("give list");
System.out.println("Request to "+i);
// receive file count from sender ServerThread
int cnt = Integer.parseInt(STmsgFrom[i].readLine());
System.out.println(i+" has files: "+cnt);
// sending source identity to receiver UserThread
UTmsgTo[cid].println(Integer.toString(i));
// send file count back to receiver UserThread
UTmsgTo[cid].println(Integer.toString(cnt));
// get and send file names to receiver
for(int j=0; j<cnt; j++) {
msg = STmsgFrom[i].readLine();
UTmsgTo[cid].println(msg);
}
}
} else if(msg.equals("get file")) {
// get source id and filename
int source = Integer.parseInt(UTmsgFrom[cid].readLine());
String fileName = UTmsgFrom[cid].readLine();
//System.out.println("get source id and filename");
// ask source about file
STmsgTo[source].println("give file");
STmsgTo[source].println(fileName);
boolean fileOk = Boolean.parseBoolean(STmsgFrom[source].readLine());
//System.out.println("ask source about file");
// telling receiver about file status
UTmsgTo[cid].println(Boolean.toString(fileOk));
//System.out.println("telling receiver about file");
if(fileOk) {
// get copy request from receiver
msg = UTmsgFrom[cid].readLine();
//System.out.println("receiver copy command");
if(msg.equals("yes copy")) {
System.out.println("Copying \'"+fileName+"\' from "+source+" to "+cid);
// tell sender to copy
STmsgTo[source].println("yes copy");
//System.out.println("tell sender copy command");
// copy from SENDER
// get file size
int FILE_SIZE = Integer.parseInt(STmsgFrom[source].readLine());
byte[] fileBytes = new byte[FILE_SIZE];
System.out.println("Get file size "+FILE_SIZE);
// get file data
int portion = STfileFrom[source].read(fileBytes,0,fileBytes.length);
int position = portion;
do {
portion = STfileFrom[source].read(fileBytes,position,fileBytes.length-position);
if(portion>=0) {
position += portion;
}
System.out.println("position = "+position);
} while(position<FILE_SIZE);
System.out.println("Get file data "+position);
// copy to RECEIVER
// send file size
UTmsgTo[cid].println(Integer.toString(FILE_SIZE));
//System.out.println("send file size");
// send file data
UTfileTo[cid].write(fileBytes,0,position);
UTfileTo[cid].flush();
//System.out.println("send file data");
System.out.println("Copying \'"+fileName+"\' complete");
} else {
// tell sender to ignore copy process
STmsgTo[source].println("no copy");
}
}
}
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
}
Client:
package client;
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws Exception {
String msg;
InetAddress inetAddress = InetAddress.getLocalHost();
String[] allPaths= {"H:\\Study\\Lab\\Network\\Assingment 2 and lab of 5 july\\Assignment\\files\\client_1_folder",
"H:\\Study\\Lab\\Network\\Assingment 2 and lab of 5 july\\Assignment\\files\\client_2_folder",
"H:\\Study\\Lab\\Network\\Assingment 2 and lab of 5 july\\Assignment\\files\\client_3_folder"};
// connecting to welcome socket
Socket server = new Socket(inetAddress,6000);
BufferedReader receive = new BufferedReader(new InputStreamReader(server.getInputStream()));
BufferedReader receiveUser = new BufferedReader(new InputStreamReader(System.in));
PrintWriter send = new PrintWriter(server.getOutputStream(),true);
// receiving serial number
int cid = Integer.parseInt(receive.readLine());
// receiving port numbers for thread sockets
int STport = Integer.parseInt(receive.readLine());
int UTport = Integer.parseInt(receive.readLine());
// connecting sockets
Socket STsocket = new Socket(inetAddress,STport);
Socket UTsocket = new Socket(inetAddress,UTport);
System.out.println("Connected to the server.\nSerial: "+cid+"\nFolder path: "+allPaths[cid]);
ServerThread st = new ServerThread(allPaths[cid],STsocket);
UserThread ut = new UserThread(cid,allPaths[cid],UTsocket);
st.start();
ut.start();
}
}
class UserThread extends Thread {
int cid;
String msg,folderPath;
BufferedReader msgFromServer,fromUser;
PrintWriter msgToServer;
// for file
DataInputStream fileFromServer;
BufferedOutputStream writeFile;
public UserThread(int cid,String folderPath,Socket socket) {
try {
this.cid = cid;
this.folderPath = folderPath;
fromUser = new BufferedReader(new InputStreamReader(System.in));
msgFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
msgToServer = new PrintWriter(socket.getOutputStream(),true);
// for file
fileFromServer = new DataInputStream(socket.getInputStream());
} catch(Exception ex) {
ex.printStackTrace();
}
}
#Override
public void run() {
//System.out.println("User Thread Started!");
while(true) {
try {
msg = fromUser.readLine();
if(msg.equals("get list")) {
// sending request to server
msgToServer.println("get list");
// getting file list from server
System.out.println("-------------------------------------------");
for(int i=0; i<2; i++) {
// getting source id
int source = Integer.parseInt(msgFromServer.readLine());
System.out.println("Source: "+source);
int cnt = Integer.parseInt(msgFromServer.readLine());
System.out.println("Files: "+cnt);
System.out.println("--------------");
for(int j=0; j<cnt; j++) {
msg = msgFromServer.readLine();
System.out.println(msg);
}
System.out.println("-------------------------------------------");
}
} else if(msg.equals("get file")) {
// GETTING A FILE
int source;
while(true) {
System.out.println("File Source: ");
try {
source = Integer.parseInt(fromUser.readLine());
if(0<=source && source<=2 && source!=cid) {
break;
} else {
System.out.println("Error: File source invalid. Try again.");
}
} catch(Exception ex) {
System.out.println("Error: File source invalid. Try again.");
}
}
System.out.println("File Name: ");
String fileName = fromUser.readLine();
// send request to server to check file
msgToServer.println("get file");
msgToServer.println(Integer.toString(source));
msgToServer.println(fileName);
// receiving file status
boolean fileOk = Boolean.parseBoolean(msgFromServer.readLine());
if(!fileOk) {
System.out.println("Error: File does not exist at source.");
} else {
System.out.println("File is available!!");
System.out.println("Want to copy \'"+fileName+"\'? (y/n)");
msg = fromUser.readLine();
if(msg.equals("y")||msg.equals("Y")) {
// tell server to copy file
msgToServer.println("yes copy");
// COPY PROCESS
// get file size
int FILE_SIZE = Integer.parseInt(msgFromServer.readLine());
System.out.println("File size: "+FILE_SIZE+" bytes.");
byte[] fileBytes = new byte[FILE_SIZE];
// get file data
int portion = fileFromServer.read(fileBytes,0,fileBytes.length);
int position = portion;
do {
portion = fileFromServer.read(fileBytes,position,fileBytes.length-position);
if(portion>=0) {
position += portion;
}
System.out.println("position = "+position);
} while(position<FILE_SIZE);
System.out.println("Total "+position+" bytes received.");
// write file data
File file = new File(folderPath + "\\" + fileName);
writeFile = new BufferedOutputStream(new FileOutputStream(file));
writeFile.write(fileBytes,0,position);
writeFile.flush();
writeFile.close();
System.out.println("Copying complete.");
} else {
msgToServer.println("no copy");
}
}
}
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
}
class ServerThread extends Thread {
String msg,folderPath;
BufferedReader msgFromServer;
PrintWriter msgToServer;
// for file
DataOutputStream fileToServer;
BufferedInputStream readFile;
public ServerThread(String folderPath,Socket socket) {
try {
this.folderPath = folderPath;
msgFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
msgToServer = new PrintWriter(socket.getOutputStream(),true);
// for file
fileToServer = new DataOutputStream(socket.getOutputStream());
} catch(Exception ex) {
ex.printStackTrace();
}
}
#Override
public void run() {
//System.out.println("Server Thread Started!");
while(true) {
try {
msg = msgFromServer.readLine();
if(msg.equals("give list")) {
//System.out.println("Request from server: "+msg);
File folder = new File(folderPath);
File[] fileList = folder.listFiles();
int cnt = fileList.length;
//System.out.println("Files: "+cnt);
// give file count back to server
msgToServer.println(Integer.toString(cnt));
// give file list back to server
for(int i=0; i<cnt; i++) {
msgToServer.println(fileList[i].getName());
}
} else if(msg.equals("give file")) {
// receive file name
String fileName = msgFromServer.readLine();
// telling server about file status
File file = new File(folderPath + "\\" + fileName);
boolean fileOk = file.exists();
msgToServer.println(Boolean.toString(fileOk));
if(fileOk) {
// getting copy request
msg = msgFromServer.readLine();
if(msg.equals("yes copy")) {
// COPY PROCESS
// send file size
int FILE_SIZE = (int)file.length();
msgToServer.println(Integer.toString(FILE_SIZE));
// read file data
readFile = new BufferedInputStream(new FileInputStream(file));
byte[] fileBytes = new byte[FILE_SIZE];
readFile.read(fileBytes,0,fileBytes.length);
readFile.close();
// send file data
fileToServer.write(fileBytes,0,fileBytes.length);
fileToServer.flush();
} // otherwise end of conversation
}
}
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
}
I am aware that I have done some unnecessary things like giving different ports to all the different sockets. Ignore them if they are not the reason of my problem.
ServerSocket.accept() is blocking, you can't call it twice from the same thread.
Every ServerSocket must run in its own thread.
i've this problem, I've a Multithreaded server running. here it's the code:
ServerSocket serverSocket=null; // defining a server socket to listen data
Socket clientSocket = null; // defining a client socket to send data
final int port=8080;
int i=0;
try {
serverSocket = new ServerSocket(port); // Opening a server socket to listen for client calls
System.out.println("Server started.");
} catch (Exception e) {
System.err.println("Port already in use.");
System.exit(1);
}
while (true) {
try {
clientSocket = serverSocket.accept(); //binding server socket to client socket incoming call and accepting call
System.out.println("Accepted connection : " + clientSocket);
i=i+1;
Thread t = new Thread(new newClientHandler(clientSocket, NodePRs[1]),"thread"+i); //Create a new thread to handle the single call coming from one client
System.out.println("Thread "+t.getName()+" is starting");
t.start(); //Starting the run method contained in newCLIENTHandler class
} catch (Exception e) {
System.err.println("Error in connection attempt.");
}
}//end while
All that i need is to let the children thread (opened every time a client request come) pass (like a function return) 4 variables when the children thread die. The newClientHandler code is this:
public class newClientHandler implements Runnable {
private final static int FILE_SIZE=6022386;
private Socket clientSocket;
private PaillierPrivateKey PrivKey;
ServerSocket servSock;
BigInteger[] msg = null;
BigInteger preamble = null;
int bytesRead;
int current = 0;
DataOutputStream dos = null;
BufferedReader dis = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
int msgtype=-1;
int num_of_rx_cnks=-1;
public newClientHandler(Socket client, PaillierPrivateKey PR) {
this.clientSocket = client;
this.PrivKey = PR;
}
//I CAN RECEIVE 3 TYPES OF MESSAGES: SHARE, THE ENCRYPTED PASSWORD, THE 4 PDMS
public void run() {
try{
ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
preamble = (BigInteger) ois.readObject();
System.out.println("Received Preamble is:"+preamble);
oos.writeObject("Received preamble");
msg =(BigInteger[]) ois.readObject();
System.out.println("Received Message is:"+msg+"\n"+msg[0]+"\n"+msg[2]);
String sPlain = Utilities.bigIntegerToString(preamble);
String[] splitArr=Pattern.compile("-").split(sPlain);
msgtype=Integer.parseInt(splitArr[0]);
num_of_rx_cnks=Integer.parseInt(splitArr[1]);
System.out.println("Message type: "+msgtype+"\n"+"Number of received cnks: "+num_of_rx_cnks);
//a questo punto ho i miei 29 biginteger. Li devo sistemare uno accanto all'altro e rimettere nel file.
switch(msgtype){
case 1: //Share received
System.out.println("Received the share");
for(int i=0;i<num_of_rx_cnks;i++){
String name = new String();
if(i<9){
name="Cyph2"+".00"+(i+1);
}
if(i>8){
name="Cyph2"+".0"+(i+1);
}
Utilities.newBigIntegerToFile(msg[i], name);
}
Utilities.retrieveShare(PrivKey, 2,"myShare");
int l, w;
BigInteger v, n, shares, combineSharesConstant;
BigInteger[] viarray=new BigInteger[5];
PaillierPrivateThresholdKey[] res = null;
try {
FileReader File= new FileReader("myShare");
BufferedReader buf=new BufferedReader(File);
String line=buf.readLine();
l = Integer.parseInt(line.split(":")[1]);
line = buf.readLine();
w = Integer.parseInt(line.split(":")[1]);
line = buf.readLine();
v = new BigInteger(line.split(":")[1]);
line = buf.readLine();
n = new BigInteger(line.split(":")[1]);
line = buf.readLine();
combineSharesConstant = new BigInteger(line.split(":")[1]);
line = buf.readLine();
shares = new BigInteger(line.split(":")[1]);
for(int i=0; i<5; i++){
line = buf.readLine();
viarray[i] = BigInteger.ZERO;
}
SecureRandom rnd = new SecureRandom();
PaillierPrivateThresholdKey result = new PaillierPrivateThresholdKey(n, l, combineSharesConstant, w, v,
viarray, shares, 2, rnd.nextLong());//il 2 qua รจ il nodeID
}catch(IOException e){
System.out.println(e);
}
break;
case 2: // Session Secret received
break;
case 3: //PDM received
break;
}//end switch
}catch(IOException ioe){
System.out.println(ioe);
}catch(ClassNotFoundException cnfe){
System.out.println(cnfe);
}finally {
try{
if (dis != null) dis.close();
if (dos != null) dos.close();
if (clientSocket!=null) clientSocket.close();
}catch (IOException e){
System.out.println(e);
}
}
}
}
I'd like to pass l, w, v, n and so on to let my main thread do some processing. How can i modify my code to do it?
Use a Callable instead of a Runnable.
Bundle the 4 variables into a class and implement Callable<YourNewClass>. Run your callable with an executor and you'll get the results in a Future<YourNewClass>.
I have a task to do this.
Create a client and server socket interaction which accepts byte data and converts the byte data data received at server in the String and send back the response with the confirmation of the data conversation with success/unsuccess as the data passed will be with fix data length format so the validation should be done at server end.
As for e.g.
there are fields which ur sending to server like,
field 1 - number
field 2 - String
field 3 as Floating number i.e. 108.50
After conversion from byte to String :
152|any msg|108.50
In Byte it will be something like this,
10101|1001010010000000011000000000|1110111011
I have tried the following programs to do this
Server.java
public class Server extends Thread
{
private ServerSocket serverSocket;
public Server(int port) throws IOException
{
serverSocket = new ServerSocket(port);
//serverSocket.setSoTimeout(100000);
}
public void run()
{
while(true)
{
try
{
Socket server = serverSocket.accept();
byte Message[]=null;
DataInputStream in =
new DataInputStream(server.getInputStream());
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = in.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
System.out.println("On this line"); //This doesnt get printed
buffer.flush();
data= buffer.toByteArray();
System.out.println(data);
String convertmsg = new String(data);
System.out.println("Msg converted "+convertmsg);
DataOutputStream out =
new DataOutputStream(server.getOutputStream());
System.out.println("below dataoutputstream");
out.write("Success".getBytes());
server.close();
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String [] args)
{
int port = 4003;
try
{
Thread t = new Server(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
client
public class Client {
public static void main(String args[]) throws IOException
{
int userinput =1;
while(userinput==1)
{
String serverName = "192.168.0.8";
int port = 4003;
try
{
System.out.println("Connecting to " + serverName
+ " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out =
new DataOutputStream(outToServer);
System.out.println("above out.wirte()");
out.write("any msg".getBytes());
InputStream inFromServer = client.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
System.out.println("converting array "+in);
byte[] data = IOUtils.toByteArray(in);
System.out.println(data);//This line doesnt get printed
//System.out.println("Server says " + in.readUTF());
client.close();
}catch(IOException e)
{
e.printStackTrace();
}
System.out.println("Enter userinput ");
DataInputStream dis = new DataInputStream(System.in);
String s = dis.readLine();
userinput = Integer.parseInt(s);
}
}
}
If i send data from client to server in bytes,it reads it and prints it.Also then the line "Enter userinput " gets printed and if the user enters '1' the program continues.
But the problem is this program given above. If i try to send data from server stating "success"(meaning the data has been converted from bytes to String successfully) then the program stucks and the cursor doesnt go below the line which are in comments "This line doesnt get printed".There is no error printed and none of the program terminates.I am new to socket programming and dont understand much about networking.
Any help will be truly appreciated.
You're reading the input until end of stream, but the peer isn't closing the connection, so end of stream never arrives.
I suggest you read and write lines, or use writeUTF() and readUTF().
I have a TCP-server client pair. The client has a thread for Handling the data which comes from the server. the problem is, before the first data is received from the server, the Buffered reader is blocked. But once the first data is received, it keeps sending 0's in between the usefull data. Does anyone have any idea why? And how to solve this?
connection = new Socket(ip, port);
output = new DataOutputStream(connection.getOutputStream());
input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
And this part is modified to handle the 0's, yet this isn't ideal:
try {
opcode = (char) input.read();
} catch (IOException ex) {
ErrorFrame erfframe = new ErrorFrame("De verbinding is verbroken voordat we de opcode van het packet konden lezen", "Herverbinden", IRIGui.ConnectionType);
}
System.out.println("Data received!!" + opcode);
int opcodenr = Character.getNumericValue(opcode);
char sensortype = '0';
try {
do {
sensortype = (char) input.read();
} while (sensortype == 0);
} catch (IOException ex) {
ErrorFrame erfframe = new ErrorFrame("De verbinding is verbroken voordat we de sensortype van het packet konden lezen", "Herverbinden", IRIGui.ConnectionType);
}
The server code:
public static void main(String argv[]) throws Exception {
ServerSocket welcomeSocket = new ServerSocket(25566);
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
int request = inFromClient.read();
System.out.println("erjioejfioe " + request);
if (request == 4) {
outToClient.writeBytes("41");
outToClient.write(5);
outToClient.writeInt(5);
outToClient.writeInt(3);
outToClient.writeInt(6);
outToClient.writeInt(5);
outToClient.writeInt(1);
}
request = 0;
request = inFromClient.read();
System.out.println("erjioejfioe " + request);
if (request == 4) {
System.out.println("SENDING THE SHIT");
outToClient.writeBytes("41");
outToClient.write(5);
outToClient.writeInt(3);
outToClient.writeInt(7);
outToClient.writeInt(2);
outToClient.writeInt(4);
outToClient.writeInt(3);
System.out.println("We get here!!");
}
break;
}
}
You are writing ints, which are 32 bits, and in your case all have three leading zero bytes, and reading chars, which are 16 bits, so every odd char you read consists of two zero bytes. This doesn't make any sense. If you write with writeInt(), read with readInt(). Same goes for all the other DataInput/OutputStream methods. Use them symmetrically.
There is no evidence here of anything not blocking.
I have a server written in C# and a client side in Android. If I send a message from client (Android) to server (c#) and from server to client, everything works fine. If I try to send one message from client , one from server, another from client, the client remains stuck at reading the message from the server. What could be the problem?
My client code is:
sendBytes("HELLOX".getBytes());
readBytes(byDataReceived);//here it gets stucked
...
try
{
int nrsend=sendBytes("HELLOX".getBytes());
readBytes(byDataReceived);
}
catch (Exception se)
{
Log.d("IdealLog","Exception: "+se.getMessage()+" ");
Toast.makeText(context, se.getMessage()+" " , 10000).show();
// MessageBox.Show(se.Message);
return false;
}
...
public static int readBytes(byte[] myByteArray) throws IOException
{
Log.d("IdealLog","readBytes-begin");
InputStream in = socket.getInputStream();
BufferedReader buffreader = new BufferedReader(new InputStreamReader(in));
String finalText = "";
String text = "";
while ((text = buffreader.readLine()) != null)
{
finalText += text;
}
myByteArray=new byte[myByteArray.length];
myByteArray=EncodingUtils.getAsciiBytes(finalText);
Log.d("IdealLog","Input Stream: "+finalText);
Log.d("IdealLog","TEST: "+EncodingUtils.getAsciiString(myByteArray));
Log.d("IdealLog","readBytes-end");
byDataReceived=myByteArray;
buffreader.close();
return myByteArray.length;//myByteArray.length;
}//readBytes end
public static int sendBytes(byte[] myByteArray) throws IOException
{
return sendBytes(myByteArray, 0, myByteArray.length);
}//sendBytes end
public static int sendBytes(byte[] myByteArray, int start, int len) throws IOException
{
if (len < 0)
{
throw new IllegalArgumentException("Negative length not allowed");
}
if (start < 0 || start >= myByteArray.length)
{
throw new IndexOutOfBoundsException("Out of bounds: " + start);
}
OutputStream out = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
// dos.writeInt(len);
if (len > 0)
{
dos.write(myByteArray, start, len);
}
int size=dos.size();
dos.flush();
return size;
}//sendBytes end
My server code:
static void Main(string[] args)
{
IPEndPoint ip = new IPEndPoint(IPAddress.Any, 1408);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(ip);
socket.Listen(10);
Console.WriteLine("Waiting for a client...");
Socket client = socket.Accept();
IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("Connected with {0} at port {1}", clientep.Address, clientep.Port);
string welcome = "HELLO&";
byte[] data = new byte[200];
client.Receive(data);
Console.WriteLine("Received data from CLIENT TEST1: {0}", System.Text.ASCIIEncoding.ASCII.GetString(data));
ASCIIEncoding asen = new ASCIIEncoding();
byte[] data2 = new byte[200];
data2 = asen.GetBytes(welcome);
client.Send(data2, data2.Length, SocketFlags.None);
//if i comment out from this 3 lines, everything is working fine
byte[] data3 = new byte[200];//this
client.Receive(data3);//this
Console.WriteLine("Received data from CLIENT TEST2: {0}", System.Text.ASCIIEncoding.ASCII.GetString(data3));//this
Console.WriteLine("Disconnected from {0}", clientep.Address);
client.Close();
socket.Close();
Console.ReadLine();
}
Modify into this:
//if i comment out from this 3 lines, everything is working fine
byte[] data3 = new byte[200];//this
client.Receive(data3);//this
Console.WriteLine("Received data from CLIENT TEST2: {0}", System.Text.ASCIIEncoding.ASCII.GetString(data3));//this
client.Send(data2, data2.Length, SocketFlags.None);
Console.WriteLine("Disconnected from {0}", clientep.Address);
client.Close();
socket.Close();
Console.ReadLine();
}