Good morning, I'm writing an application where the socket server is in C # (because there are some drivers that have to be in C #) and the client in Java. I can make the communication perfectly between them, however when passing data, I have the following error:
System.ArgumentOutOfRangeException: Argument specified was outside the range of valid values. Parameter Name: size at System.Net.Sockets.NetworkStream.Read (Byte [] buffer, Int32 offset, Int32 size) in tests.handleClinet.doChat () on d: \ c # \ socket \ tests \ handleClinet.cs: line 40
Server C # code:
//Class to handle each client request separatly
public class handleClinet
{
TcpClient clientSocket;
string clNo;
public void startClient(TcpClient inClientSocket, string clineNo)
{
this.clientSocket = inClientSocket;
this.clNo = clineNo;
Thread ctThread = new Thread(doChat);
ctThread.Start();
}
private void doChat()
{
int requestCount = 0;
byte[] bytesFrom = new byte[10000];
string dataFromClient = null;
Byte[] sendBytes = null;
string serverResponse = null;
string rCount = null;
requestCount = 0;
while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
Console.WriteLine(" >> " + (int)clientSocket.ReceiveBufferSize);
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
Console.WriteLine(" >> " + "From client-" + clNo + dataFromClient);
rCount = Convert.ToString(requestCount);
serverResponse = "Server to clinet(" + clNo + ") " + rCount;
sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
Console.WriteLine(" >> " + serverResponse);
}
catch (Exception ex)
{
Console.WriteLine(" >> " + ex.ToString());
return;
}
}
}
}
Client code: Java
public static void main(String[] args) throws IOException {
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 9999);
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();
}
New client in Java:
public class Cliente {
public static void main(String[] args) {
try {
Socket s = new Socket("127.0.0.1", 9999);
InputStream i = s.getInputStream();
OutputStream o = s.getOutputStream();
String str;
while(true){
byte[] line = new byte[100];
System.in.read(line);
o.write(line);
i.read(line);
str = new String(line);
System.out.println(str.trim());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Thanks for the help.