My server-client application consists of the following modules:
client (written in Java) connects to server and sends a file;
server (written in C) receives the file and sends a char array message.
The problem is that after receiving the file, the server is unable to send the message or the client is unable to receive it.
Here is my code for server application:
int main(int argc , char *argv[])
{
WSADATA wsa;
SOCKET s , new_socket;
struct sockaddr_in server , client;
int c, bytecount, nr_transf, rest_byte, i, bytesRead;
int recv_size, file_size;
char message[1000];
char buffer[1000];
int buffer_len = 1000;
FILE *f = fopen("out.jpg", "wb");
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
printf("Failed. Error Code : %d", WSAGetLastError());
return 1;
}
printf("Initialised.\n");
//Create a socket
if((s = socket(AF_INET, SOCK_STREAM, 0 )) == INVALID_SOCKET)
{
printf("Could not create socket : %d" , WSAGetLastError());
getch();
return 0;
}
printf("Socket created.\n");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(8888);
//Bind
if(bind(s, (struct sockaddr*)&server, sizeof(server)) == SOCKET_ERROR)
{
printf("Bind failed with error code : %d" , WSAGetLastError());
getch();
return 0;
}
puts("Bind done");
//Listen to incoming connections
listen(s, 3);
//Accept and incoming connection
printf("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
new_socket = accept(s, (struct sockaddr*)&client, &c);
if (new_socket == INVALID_SOCKET)
{
printf("accept failed with error code : %d", WSAGetLastError());
getch();
return 0;
}
printf("Connection accepted");
//Receive image
while((bytesRead = recv(new_socket, buffer, buffer_len, 0)) > 0)
{
fwrite(buffer, 1, bytesRead, f);
}
fclose(f);
printf("\nReceive finished!");
//Send messsage
char my_message[100];
strcpy(my_message, "Hello World!");
send(new_socket, my_message, strlen(my_message), 0);
closesocket(s);
WSACleanup();
getch();
return 0;
}
And the code for client application:
public class MyClass
{
public static void main(String[] args)
{
String fileName = "1.jpg", receiveMessage;
File a_file = new File(fileName);
int j;
OutputStream output = null;
InputStream input = null;
ObjectInputStream in = null;
Socket socket = null;
try
{
// Create a socket
socket = new Socket("192.168.0.122", 8888);
FileInputStream fileInputStream = new FileInputStream(fileName);
byte[] buffer = new byte[1000];
int bytesRead = 0;
output = socket.getOutputStream();
input = socket.getInputStream();
while((bytesRead = fileInputStream.read(buffer))>0)
{
output.write(buffer,0,bytesRead);
}
fileInputStream.close();
System.out.println("Send finished!");
input.read(buffer);
System.out.println("Receive finished!");
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
in.close();
output.close();
socket.close();
}
catch(Exception e)
{
}
}
}
}
Any ideas to solve this problem? Thanks in advance!
It's because you have blocking sockets. When a socket is created (by connecting or by accepting) it is in blocking mode. This means that if there is no data to receive it will not return, effectively blocking the caller.
So after you received the last byte in the loop in the server, the recv call will block indefinitely.
On Windows with winsockets, you use the ioctlsocket function to make a socket blocking or non-blocking. The linked reference have an example which shows hot to make a socket blocking or non-blocking.
Related
I have a Server in C and a client in Java(TCP connection). After I connect them I send the first message from client then a response from the server and everything is ok at this point(client writes in the console the string received) when I send another message to the server and the server gives a response, this response is put at the end of a long String with unkown first characters. For example on the client side I see:
Send a message: type and press Enter key
HELLO
Server: HI
HELLO AGAIN
Server:
HELLO HELLO
Server:
The output on the server side is ok ( both client's and server's messages are seen)
Here is my server:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 10011
int main(){
int socketfd, ret;
struct sockaddr_in serverAddr;
int newSocket;
struct sockaddr_in newAddr;
socklen_t addr_size;
char buffer[1024];
pid_t childpid;
socketfd = socket(AF_INET,SOCK_STREAM,0);
if(socketfd < 0){
printf("\n error in socket creation");
return -1;
}
printf("\n Server socket is created\n");
memset(&serverAddr, '\0', sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PORT);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
ret = bind(socketfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
if(ret < 0){
printf("Error in binding\n");
return -1;
}
printf("[*]Bind to port %d\n", PORT);
if(listen(socketfd, 10) == 0){
printf("Listening...\n");
}else{
printf("Error in binding\n");
}
newSocket = accept(socketfd, (struct sockaddr*)&newAddr, &addr_size);
if( newSocket < 0){
printf("No socket\n");
exit(1);
}
int size = 1024;
char buff[size];
char sbuff[size];
int n;
int reader;
memset(buff, 0, size);
memset(sbuff, 0, size);
// infinite loop for receiving and sending
for (;;) {
// read the message from client and copy it in buffer
reader = recv(newSocket, buff, 1024 * sizeof(char), 0);
if (reader == -1) {
perror("recv()");
break;
} else if (reader == 0) {
break;
} else {
// print buffer which contains the client contents
printf("From client: %s\t To client : ", buff);
// if msg contains "Exit" then server exit and chat ended.
if (strncmp("exit", buff, 4) == 0) {
printf("Server Exit...\n");
break;
}
bzero(buff, size);
n = 0;
// copy server message in the buffer
while ((sbuff[n++] = getchar()) != '\n');
// and send that buffer to client
write(newSocket, sbuff, sizeof(sbuff));
bzero(sbuff,size);
}
}
close(newSocket);
return 0;
}
and here is my client:
import java.io.*;
import java.net.*;
public class ClientJava
{
public static void main(String[] args) throws Exception
{
Socket sock = new Socket("127.0.0.1", 10011);
// reading from keyboard (keyRead object)
BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
// sending to client (pwrite object)
OutputStream ostream = sock.getOutputStream();
PrintWriter pwrite = new PrintWriter(ostream, true);
// receiving from server ( receiveRead object)
InputStream istream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream), 1024);
System.out.println("Send a message: type and press Enter key");
String receiveMessage, sendMessage;
while(true)
{
sendMessage = keyRead.readLine(); // keyboard reading
pwrite.println(sendMessage); // sending to server
pwrite.flush(); // flush the data
// for(int i=0; i<1024;i++){
// String s=receiveRead.read();
// receiveMessage[i]=s;
// if(s == ">") {
// return i;
// }
// }
// System.out.println(receiveMessage);
receiveMessage = receiveRead;
if((receiveMessage) != "0") //receive from server
{
System.out.println(receiveMessage); // displaying at DOS prompt
}
//removeNonAscii(receiveMessage);
//replaceUnreadable(receiveMessage);
receiveMessage = receiveMessage.substring(0,0);
}
}
private static String removeNonAscii(String s){
StringBuffer sb = new StringBuffer();
for(int i=0; i<s.length(); ++i){
if(s.charAt(i) < 128){
sb.append(s.charAt(i));
}
}
return sb.toString();
}
private static String replaceUnreadable(String s){
String clean = s.replaceAll("\\P{Print}", "");
return clean;
}
}
After debugging I found out that when receiving the message for the second time recieveMessage is full of empty characters and the actual message goes to the end of the String(so it is not visible in the console). How can I clean the String or put the message at the beginning of it? Thanks.
Solved: I used this method
private static String replaceUnreadable(String s){
String clean = s.replaceAll("\\P{Print}", "");
return clean;
}
and it worked
My C++ program which is the client connects with the Java server . From the time of connection establishment the C++ client sends a block of data of size ~1MB to 3MB in a fixed frequency( say 10 sec).
My Java server opens a socket
Socket client = new ServerSocket(14001, 10).accept();//blocking
ReceiveThread st = new ReceiveThread(client);
and it receives the data from client as below.
private String getDataFromSocket(BufferedReader reader) throws IOException
{
int byteLimit = 1024*1024*2; //2 MB
String output = "";
char[] charArray = null;
int availableSize = is.available();
if(availableSize < 1) // If available size is 0 just return empty
{
return output;
}
while(availableSize > byteLimit) // Reads 2MB max if available size is more than 2 MB
{
charArray = new char[byteLimit];
reader.read(charArray,0,charArray.length);
output += new String(charArray);
availableSize = is.available();
}
charArray = new char[availableSize];
reader.read(charArray,0,charArray.length);
output = output +new String(charArray);
return output;
}
The above GetDataFromSocket keeps on checking for available data till the socket is closed gracefully.
the C++ connects with the Java server
void CreateSocket()
{
int err, nRet = 0;
sockfd = 0;
WORD wVersionRequested;
WSADATA wsaData;
//WSACleanup();// Is this needed?
wVersionRequested = MAKEWORD(1, 1);
while (1)
{
err = WSAStartup(wVersionRequested, &wsaData);
if (err != 0)
{
Sleep(50);
continue;
}
else
{
break;
}
}
while (1)
{
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1 || sockfd == INVALID_SOCKET)
{
Sleep(50);
continue;
}
else
{
nRet = 1;
break;
}
}
}
void ConnectWithServer()
{
int nRet = 0;
char myname[256] = { 0 };
int wsaErr = 0, portNum = 0, retryCount=0;
struct hostent *h = NULL;
struct sockaddr_in server_addr;
gethostname(myname, 256);
portNum = 1401;
while (1)
{
if ((h = gethostbyname(myname)) != NULL)
{
memset(&server_addr, 0, sizeof(struct sockaddr_in));
memcpy((char *)&server_addr.sin_addr, h->h_addr, h->h_length);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(portNum);
server_addr.sin_addr = *((struct in_addr*) h->h_addr);
}
if (0 == connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)))
{
nRet = 1;
break;
}
else
{
}
Sleep(50);
}
}
The connection establishment to the server is done by the above two functions and it returns success. After these steps i am sending the data buffer to the Java server once in every 10 seconds.
while(index<retryCount)
{
string toSend = wstring_to_utf8(sRequestData);
nRet = send(sockfd, toSend.c_str(), toSend.length(), 0);
if (nRet == SOCKET_ERROR)
{
wsaErr = WSAGetLastError();
Sleep(DEFAULT);
index++;
}
else if(nRet == toSend.length())
{
break;
}
else
{
index = 0;
}
}
The problem here is, after some hours of send and receive from C++ to Java server , the send gets hanged for infinite time. The execution never comes out from the send() function. But after the hang if i abruptly close the Java server , then the send returns socket error and again works well for some hours and the hang still occurs.
As i mentioned i keep on sending data to server of size varied from 1 MB to 3 MB ten seconds once. What could be the issue here? How can i sort this out?
i'm trying to write a program which uses sockets to send and receive an image.
The Java source should run on android devices. But the class TCP also works on normal java applications.
To be hornest it is just a feature of my whole program.
First of all i want to share my source codes:
Java :
Async (to use it on newer Versions of android >5.**)
class Async extends AsyncTask<String, TCPClient, String> {
#Override
protected String doInBackground(String... args) {
TCPClient cp = new TCPClient();
try {
if (args[1].equals("remote"))
cp.TCPSend(args[0]);
else {
cp.TCPrecv();
}
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
}
TCP Client:
class TCPClient
{
public void TCPSend(String sentence) throws IOException
{
String modifiedSentence;
Socket clientSocket = new Socket("192.168.0.14", 1334);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
public Bitmap TCPrecv() throws IOException
{
Socket clientSocket = new Socket("192.168.0.14", 1331);
DataInputStream dis;
dis = new DataInputStream(clientSocket.getInputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String size_pic = inFromServer.readLine();
int bytesize=Integer.parseInt(size_pic);
int bytesRead=0;
byte[] pic = new byte[bytesize];
int read=0;
while(read < bytesize && !(bytesRead ==-1)) {
bytesRead = dis.read(pic, 0, 10239);
read += bytesRead;
}
return BitmapFactory.decodeByteArray(pic, 0, pic.length);
}
}
This programm reads a image as a ByteArray. It works for 36/37 packets. Don't matter which size of packets i use. The last packet get lost.
I write some own codes of C Servers but the best code i found on this forum.
The Code snipe contains client and server functions and it works perfect.
But the connection of the the Java Programm works not for all packets.
C Code :
void error(const char *msg)
{
perror(msg);
exit(1);
}
int send_image(int socket){
FILE *picture;
int size, read_size, stat, packet_index;
char send_buffer[10240], read_buffer[256];
packet_index = 1;
picture = fopen("../MR.PNG", "r");
printf("Getting Picture Size\n");
if(picture == NULL) {
printf("Error Opening Image File"); }
fseek(picture, 0, SEEK_END);
size = ftell(picture);
fseek(picture, 0, SEEK_SET);
printf("Total Picture size: %i\n",size);
//Send Picture Size
printf("Sending Picture Size\n");
char *ptr=(char *) malloc(500);
sprintf(ptr,"%d",size);
strcat(ptr,"\n");
write(socket,ptr,20);
//Send Picture as Byte Array
printf("Sending Picture as Byte Array\n");
/* do { //Read while we get errors that are due to signals.
stat=read(socket, &read_buffer , 255);
printf("Bytes read: %i\n",stat);
} while (stat < 0);*/
printf("Received data in socket\n");
printf("Socket data: %c\n", read_buffer);
while(!feof(picture)) {
//while(packet_index = 1){
//Read from the file into our send buffer
read_size = fread(send_buffer, 1, sizeof(send_buffer)-1, picture);
//Send data through our socket
do{
stat = write(socket, send_buffer, read_size);
}while (stat < 0);
printf("Packet Number: %i\n",packet_index);
printf("Packet Size Sent: %i\n",read_size);
printf(" \n");
printf(" \n");
packet_index++;
//Zero out our send buffer
bzero(send_buffer, sizeof(send_buffer));
int send_image(int socket){
FILE *picture;
int size, read_size, stat, packet_index;
char send_buffer[10240], read_buffer[256];
packet_index = 1;
picture = fopen("../MR.PNG", "r");
printf("Getting Picture Size\n");
if(picture == NULL) {
printf("Error Opening Image File"); }
fseek(picture, 0, SEEK_END);
size = ftell(picture);
fseek(picture, 0, SEEK_SET);
printf("Total Picture size: %i\n",size);
//Send Picture Size
printf("Sending Picture Size\n");
write(socket, (void *)&size, sizeof(int));
//Send Picture as Byte Array
printf("Sending Picture as Byte Array\n");
do { //Read while we get errors that are due to signals.
stat=read(socket, &read_buffer , 255);
printf("Bytes read: %i\n",stat);
} while (stat < 0);
printf("Received data in socket\n");
printf("Socket data: %c\n", read_buffer);
while(!feof(picture)) {
//while(packet_index = 1){
//Read from the file into our send buffer
read_size = fread(send_buffer, 1, sizeof(send_buffer)-1, picture);
//strcat(send_buffer,"\n");
//Send data through our socket
do{
stat = write(socket, send_buffer, read_size);
}while (stat < 0);
printf("Packet Number: %i\n",packet_index);
printf("Packet Size Sent: %i\n",read_size);
printf(" \n");
printf(" \n");
packet_index++;
//Zero out our send buffer
bzero(send_buffer, sizeof(send_buffer));
}
}
}
}
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[256];
char contentbuffer[255];
struct sockaddr_in serv_addr, cli_addr;
int n;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = 1331;
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr,
sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd,5);
clilen = sizeof(cli_addr);
while(1)
{
newsockfd = accept(sockfd,
(struct sockaddr *) &cli_addr,
&clilen);
if (newsockfd < 0)
error("ERROR on accept");
int i=0;
send_image(newsockfd);
}
close(newsockfd);
close(sockfd);
return 0;
}
I dont understand why this code 2 times works without problems. But without any changes the last bytes get lost... :-/
Sorry, my english is very badly. But i realy need help. It is so frustrating to debug an program without the knowlege to understand what the problem is.
Sorry again. I have trouble with the code snipes system. It want work on Class TCP Client.
Thank for your attention.
MFG Neks
Edit: After some comments i'm modified my Java Code. Now the same code works on a real Java Programm with Java EE IDE. This program works fine. But the same code want work on Android. I don't understand why. I can post pics of the debugging sessions.
package com.vib;
import java.io.;
import java.net.;
class NewTcpClient {
#SuppressWarnings("resource")
public void TCPrecv() throws IOException {
Socket clientSocket = new Socket("192.168.0.14", 1331);
DataInputStream dis;
dis = new DataInputStream(clientSocket.getInputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
String size_pic = inFromServer.readLine();
int bytesize = Integer.parseInt(size_pic);
int bytesizeread = 10239;
int bytesRead = 0;
byte[] pic = new byte[bytesize];
int read = 0;
int count=0;
while (read < bytesize)
{
bytesRead = dis.read(pic, 0, bytesizeread);
read += bytesRead;
count++;
}
clientSocket.close();
System.out.println(pic);
}
public static void main(String argv[]) throws Exception {
NewTcpClient tcp = new NewTcpClient();
tcp.TCPrecv();
}
}
I don't understand whats going on... i uses this programm on normal IDE now for 3 houres... now it want work... without any changes. How can i debugg something so mystil? ^^
After a break of 2 hours the program works fine. What can be a reason for this bug.
I have 2 socket clients and 2 socket servers, one of each in C and Java and all running on my local machine as processes.
They can all talk to each other successfully except the C socket and Java server. They connect successfully but when I type input into the C client, the enter key does not finish the message and send it to the Java server in the same manner it does when communicating with the C server.
Any insight would be greatly appreciated.
Java Server:
import java.net.*;
import java.io.*;
public class SimpleServer extends Thread
{
private ServerSocket serverSocket;
String clientmsg = "";
public SimpleServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
}
public void run()
{
while(true)
{
try
{
System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to " + server.getRemoteSocketAddress());
DataInputStream in = new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to "
+ server.getLocalSocketAddress() + "\nGoodbye!");
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 = Integer.parseInt(args[0]);
try
{
Thread t = new SimpleServer(port);
t.start();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
C client:
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#include <netdb.h>
void error(char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char *argv[])
{
int sockfd, portno;
struct sockaddr_in serv_addr;
struct hostent *server;
int n;
char buffer[256];
if (argc < 3)
{
error("ERROR, no port provided");
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
error("ERROR opening socket");
}
server = gethostbyname(argv[1]);
if (server == NULL)
{
error("ERROR, host not found\n");
}
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[2]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
if (connect(sockfd,(struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
error("ERROR connecting to server");
}
printf("Enter a message for the server: ");
bzero(buffer,256);
fgets(buffer,sizeof(buffer),stdin);
n = write(sockfd,buffer,strlen(buffer));
if (n < 0)
{/
error("ERROR writing to socket");
}
bzero(buffer,256);
n = read(sockfd,buffer,255);
if (n < 0)
{
error("ERROR reading from socket");
}
printf("%s\n", buffer);
return 0;
}
I would suggest to use BufferedReader and PrintWriter as follow,
BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream())); // Bufferreader from socket
PrintWriter out = new PrintWriter(socket.getOutputStream(), true); // printwriter from socket
You can simply use them as ,
in.readLine(); // read a line
out.println(); // write a line
So updated code would look like,
Socket server = serverSocket.accept();
System.out.println("Just connected to " + server.getRemoteSocketAddress());
BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream()));
System.out.println(in.readline());
PrintWriter out = new PrintWriter(server.getOutputStream());
out.println("Thank you for connecting to ");
Additionally if i'm correct this approach would fulfill line terminal conditions for both Java and C.
From the readUTF() documentation :
First, two bytes are read and used to construct an unsigned 16-bit integer in exactly the manner of the readUnsignedShort method . This integer value is called the UTF length and specifies the number of additional bytes to be read.
In your C client, you are not sending these two bytes. Of course, this is also true for writeUTF().
Data to be read by readUTF() must be sent by writeUTF(), or something that can produce the same protoco:l: see the Javadoc. As your sender is C this is not practical, so you should use a different read API, for example readLine(), with suitable adjustment at the sender.
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();
}