I wrote that code after some research on the internet to send files throught computers at the same network. But, sometimes it's sending the files corrupted or with low quality (if the file is a picture). Can you check this out?
Note: I want to send only files with 10MB size.
Server
class Server
{
IPEndPoint end;
Socket sock;
public Server()
{
end = new IPEndPoint(IPAddress.Any, 5656);
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Bind(end);
}
public static string path;
public static string MsgCurrent = "Stopped";
public void StartServer()
{
try
{
MsgCurrent = "Starting...";
sock.Listen(100);
MsgCurrent = "Works and looks for files";
Socket clientSock = sock.Accept();
byte[] clientData = new byte[1024 * 1024 * 10]; //count per byte
int receivedByteLen = clientSock.Receive(clientData);
MsgCurrent = "Receiving file ...";
int fNameLen = BitConverter.ToInt32(clientData, 0);
string fName = Encoding.ASCII.GetString(clientData, 4, fNameLen);
BinaryWriter write = new BinaryWriter(File.Open(path + "/" + fName, FileMode.Append));
write.Write(clientData, 4 + fNameLen, receivedByteLen - 4 - fNameLen);
MsgCurrent = "Saving file....";
write.Close();
clientSock.Close();
MsgCurrent = "The file was received";
}
catch
{
MsgCurrent = "Error, the file was not received";
}
}
}
Client
class Client
{
public static string ipsendf;//added
public static string MsgCurrent = "Idle";
public static void SendFile(string fName)
{
try
{
IPAddress ip = IPAddress.Parse(ipsendf); //127.0.0.1 in "" as string
IPEndPoint end = new IPEndPoint(ip, 5656);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
string path = "";
fName = fName.Replace("\\", "/");
while (fName.IndexOf("/") > -1)
{
path += fName.Substring(0, fName.IndexOf("/") + 1);
fName = fName.Substring(fName.IndexOf("/") + 1);
}
byte[] fNameByte = Encoding.ASCII.GetBytes(fName);
if (fNameByte.Length > 10 * 1024 * 1024) //count per byte
{
//MsgCurrent = "File is greater than 850 kb";
MsgCurrent = "File is greater than 10MB";
return;
}
MsgCurrent = "Buffering...";
byte[] fileData = File.ReadAllBytes(path + fName);
byte[] clientData = new byte[4 + fNameByte.Length + fileData.Length];
byte[] fNameLen = BitConverter.GetBytes(fNameByte.Length);
fNameLen.CopyTo(clientData, 0);
fNameByte.CopyTo(clientData, 4);
fileData.CopyTo(clientData, 4 + fNameByte.Length);
MsgCurrent = "Connecting to server ...";
sock.Connect(end);
MsgCurrent = "File sending ...";
sock.Send(clientData);
MsgCurrent = "Disconnecting...";
sock.Close();
MsgCurrent = "The file was sent ..";
}
catch (Exception ex)
{
//do nothing
}
}
}
The default receive size for a socket is 8,192 bytes (for reference). So from your code it looks like on the server, you're only reading the first 8,192 bytes of the message.
You can either increase that buffer size to match the size of the 10MB clientData buffer you allocate, for example, some where after .Accept() and before Receive()..
clientSock.ReceiveBufferSize = 1024 * 1024 * 10;
Or, receive in chunks by checking if there's anything left to read and keep filling up your local buffer. You'll probably get away with the potenitally massive message on a local network though, generally speaking in chunks would be the normal way to do it.
Also, you're using FileMode.Append in the write of the file in server, whereas I would have thought you want FileMode.Create. Otherwise, if you send the same file twice you'll get a 20MB file instead of a 10MB one.
Related
Java (client side)
relevant code
// Create the encoder and decoder for targetEncoding
Charset charset = Charset.forName("UTF-8");
CharsetDecoder decoder = charset.newDecoder();
CharsetEncoder encoder = charset.newEncoder();
byte[] underlyingBuffer = new byte[100000];
ByteBuffer buffer = ByteBuffer.wrap(underlyingBuffer);
System.out.println("first buffer remaining" + buffer.remaining() + " "
+ buffer.limit());
buffer.order(ByteOrder.LITTLE_ENDIAN);
try {
Socket client = new Socket("localhost", 8080);
OutputStream oStream = client.getOutputStream();
InputStream iStream = client.getInputStream();
//String secondFilePath = "C:\\Users\\pedge\\Desktop\\readData.csv";//this is csv file
//long secondFileLength = ReadFileToCharArray(buffer,secondFilePath , encoder);
String inputImage = "C:\\Users\\pedge\\Desktop\\Desert.jpeg";// image to transfer
ReadFileToCharArray(buffer,inputImage , encoder);
//imageWrite(oStream, inputImage);
buffer.flip();
int dataToSend = buffer.remaining();
int remaining = dataToSend;
while (remaining > 0) {
oStream.write(buffer.get());
--remaining;
}
public static long ReadFileToCharArray(ByteBuffer buffer, String filePath,
CharsetEncoder encoder) throws IOException {
fileCount++;
System.out.println("second buffer remaining" + buffer.remaining() + " "
+ buffer.limit());
StringBuilder fileData = new StringBuilder(100);
File file = new File(filePath);
System.out.println("Size of file ["+fileCount+"] sent is ["+file.length()+"]");
BufferedReader reader = new BufferedReader(new FileReader(filePath));
char[] buf = new char[10000000];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1) {
System.out.println(numRead);
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
buf = new char[1000000];
}
reader.close();
CharBuffer charBuffer = CharBuffer.wrap(fileData.toString()
.toCharArray());
System.out.println("char buffer " + charBuffer.remaining());
ByteBuffer nbBuffer = null;
try {
nbBuffer = encoder.encode(charBuffer);
} catch (CharacterCodingException e) {
throw new ArithmeticException();
}
buffer.putInt(nbBuffer.limit());
System.out.println("buffer information" + buffer.position() + " "
+ buffer.limit() + " nbBuffer information" + nbBuffer.position()
+ " " + nbBuffer.limit());
buffer.put(nbBuffer);
return file.length();
}
C# (Server Side)
static void Main(string[] args)
{
try
{
Run(args);
}
catch (Exception e)
{
Console.Error.WriteLine(e);
}
}
static void Run(string[] args)
{
TcpListener listener = new TcpListener(8080);
listener.Start();
while (true)
{
using (TcpClient client = listener.AcceptTcpClient())
{
try
{
Read(client);
}
catch (Exception e)
{
Console.Error.WriteLine(e);
}
}
}
}
static void Read(TcpClient client)
{
String csvFile4Parsing = "C:\\Users\\pedge\\Desktop\\newReadData.csv";// csv file created from byte stream
Console.WriteLine("Got connection: {0}", DateTime.Now);
NetworkStream ns = client.GetStream();
BinaryReader reader = new BinaryReader(ns);
int length = reader.ReadInt32();
Console.WriteLine("Length of csv is [" + length + "]");
byte[] fileArray = reader.ReadBytes(length);
File.WriteAllBytes(csvFile4Parsing, fileArray);//bytes from stream, written to csv`
Now i am able to transfer the image from java to C# and a file is then created by c#(works perfect)
But when i try to send the image(same as like CSV), it doesn't work at all and even the bytes received at the server end are different from that of client end. I have spent hours now on this with no success. :/
and help will be much appreciated. thanks.
CSV data is text and might require the CharsetEncoder you are using to process the stream before sending it to the C#, but image data is binary and you only want to send a bit-for-bit copy of the data. The problem is likely to be that the stream encoder mistakenly interprets some binary sequences in the image data as text characters that need to be encoded and mangles them.
Just use plain binary stream read and write on both sides (you are already doing it in C#) and confirm that the data is exactly the same. If it isn't, post a hex sample of how it is different.
Finally the solved this issue.
Java(Client)
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class ImageServer {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8000);
//code to send image
File file = new File("C:\\Users\\ashish\\Desktop\\image.jpg");
FileInputStream fileInputStream = new FileInputStream(file);
int count=0;
byte[] fileBytes = new byte[(int)file.length()];
int content;
OutputStream outputStream = socket.getOutputStream();
while((content = fileInputStream.read(fileBytes)) != -1){
outputStream.write(fileBytes, 0, (int)file.length());
}
System.out.println("file size is "+ fileBytes.length);
for(byte a : fileBytes){System.out.println(a);}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
C#(Server)
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace Test.SendImageClient
{
public class Program
{
static void Main(string[] args)
{
TcpListener tcpListener = null;
try
{
IPAddress ipadress = IPAddress.Parse("127.0.0.1");
tcpListener = new TcpListener(ipadress, 8000);
/* Start Listeneting at the specified port */
tcpListener.Start();
byte[] bytes = new byte[6790];
byte[] finalBytes;
while(true){
TcpClient client = tcpListener.AcceptTcpClient();
Console.WriteLine("Connected!");
NetworkStream stream = client.GetStream();
int i;
do
{
i = stream.Read(bytes, 0, bytes.Length);
finalBytes = new byte[i];
Console.WriteLine("Size dynamically is "+i);
for (int n = 0; n < i; n++ )
{
finalBytes[n] = bytes[n];
}
}while(stream.DataAvailable);
File.WriteAllBytes("C:\\Users\\ashish\\Desktop\\newImage.jpg", finalBytes);
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
tcpListener.Stop();
}
}
}
}
I'm developing a web application for a handheld RFID reader (windows CE),
and I'm trying to send an XML file from the RFID reader to a laptop throgh wireless network or GPRS. The code works properly with "windows form application" on MS visual studio, but when I try to use it with "smart device application" it doesn't work... an error appears for the "ReadAllBytes" method:
System.IO.File dose not contain a definition for ReadAllBytes
Please help me to handle this error.
Thanks.
The code:
private void button1_Click(object sender, EventArgs e)
{
try
{
string IpAddressString = "10.1.1.104";
IPEndPoint ipEnd_client = new
IPEndPoint(IPAddress.Parse(IpAddressString), 5656);
Socket clientSock_client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.IP);
string fileName = "student.XML";
string filePath =#"My Device\";
fileName = fileName.Replace("\\", "/");
while (fileName.IndexOf("/") > -1)
{
filePath += fileName.Substring(0, fileName.IndexOf("/") + 1);
fileName = fileName.Substring(fileName.IndexOf("/") + 1);
}
byte[] fileNameByte = Encoding.UTF8.GetBytes(fileName);
if (fileNameByte.Length > 5000 * 1024)
{
curMsg_client = "File size is more than 5Mb,
please try with small file.";
MessageBox.Show("File size is more than 5Mb,
please try with small file.");
return;
}
MessageBox.Show("Buffering ...");
string fullPath = filePath + fileName;
byte[] fileData =File.ReadAllBytes(fullPath);
byte[] clientData = new byte[4 + fileNameByte.Length +
fileData.Length];
//byte[] clientData = new byte[4 + fileNameByte.Length];
byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);
fileNameLen.CopyTo(clientData, 0);
fileNameByte.CopyTo(clientData, 4);
fileData.CopyTo(clientData, 4 + fileNameByte.Length);
MessageBox.Show("Connection to server ...");
clientSock_client.Connect(ipEnd_client);
MessageBox.Show("File sending...");
clientSock_client.Send(clientData, 0, clientData.Length, 0);
MessageBox.Show("Disconnecting...");
clientSock_client.Close();
MessageBox.Show ("File [" + fullPath + "] transferred.");
}
catch (Exception ex)
{
if (ex.Message == "No connection could be made
because the target machine actively refused it")
{
MessageBox.Show ("File Sending fail. Because
server not running.");
}
else
{
MessageBox.Show ("File Sending fail." +
ex.Message.ToString());
}
}
}
It's because, as the error states, ReadAllBytes doesn't exist in the Compact Framework. You have to use an overload of Read to get the data.
Something along these lines:
using (var reader = File.OpenRead(filePath))
{
var fileData = new byte[reader.Length];
reader.Read(fileData, 0, fileData.Length);
}
I'm trying to send a couple of data via Sockets, so it's converted to bytes and then back to String on the Server. But I can only do one apparently.
Server code:
static void Read(IAsyncResult ar)
{
int fileNameLen = 1;
//int userNameLen = 9;
State newState = (State)ar.AsyncState; //gets state of Socket
Socket handler = newState.Socket_w; //passes Socket to handler
int bytesRead = handler.EndReceive(ar); //terminates Data Receive from Socket.
if (bytesRead > 0)
{
if (flag == 0)
{
fileNameLen = BitConverter.ToInt32(newState.buffer, 0); //gets filename length
fileName = Encoding.UTF8.GetString(newState.buffer, 4, fileNameLen); //gets filename
//userNameLen = BitConverter.ToInt32(newState.buffer, 8);
//getUsername = Encoding.UTF8.GetString(newState.buffer, 8, fileNameLen);
flag++;
}
}
}
Client code:
internal static void uploadFile(string host, string username, string getGame, string filename, string filepath)
{
byte[] m_clientData;
Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
byte[] fileName = Encoding.UTF8.GetBytes(username + "_" + filename);
byte[] fileData = File.ReadAllBytes(filepath);
byte[] fileNameLen = BitConverter.GetBytes(fileName.Length);
//byte[] sendUsername = Encoding.UTF8.GetBytes(username);
//byte[] sendUsernameLen = BitConverter.GetBytes(sendUsername.Length);
//byte[] sendGame = Encoding.UTF8.GetBytes(getGame);
//byte[] sendGameLen = BitConverter.GetBytes(sendGame.Length);
m_clientData = new byte[4 + fileName.Length + fileData.Length];
fileNameLen.CopyTo(m_clientData, 0);
fileName.CopyTo(m_clientData, 4);
fileData.CopyTo(m_clientData, 4 + fileName.Length);
//sendUsernameLen.CopyTo(m_clientData, 0);
//sendUsername.CopyTo(m_clientData, 4);
//sendGameLen.CopyTo(m_clientData, 0);
//sendGame.CopyTo(m_clientData, 4);
clientSock.Connect(host, 8889);
clientSock.Send(m_clientData); //tofix exception
clientSock.Close();
}
I can't seem to decrypt it properly over on Server. Can anyone help me with the buffersizes and whatnot?
Read does not know anything about what was sent; TCP is basically just a stream - so there is absolutely nothing to say that you have all the data in one call to Read; you could have:
exactly the amount of data you sent
part of one message
17 messages
the end of one message and the start of the next
1 solitary byte from a message
You need to devise some kind of framing protocol that lets the receiver know when they have an entire message. That could be as simple as a length prefix, or can be more complex. You should then buffer the data in memory (or process it gradually) until you have the entire message. One call to Read is very unlikely to represent a single and complete message. Indeed, this is guaranteed not to be the case if a message is larger than your newstate.buffer, but you can get the same result even for small messages and a large buffer.
Can anyone give me a small tutorial on how to send file from java server to c# client and on receive complete acknowledgment message from c# to java. Actually I'm new to C# and dont know how to do socket programming. I'm stuck in it since long. Tried many codes. Some codes receive incomplete files some stuck in infinite loop. Please help me in this regard.
Thanks
EDIT
Here is what I have tried:
C# Server:
{
IPAddress ipAd = IPAddress.Parse("192.168.1.131");
// use local m/c IP address, and
// use the same in the client
/* Initializes the Listener */
TcpListener myList = new TcpListener(ipAd, 5600);
/* Start Listeneting at the specified port */
myList.Start();
Console.WriteLine("The server is running at port 5600...");
Console.WriteLine("The local End point is :" +
myList.LocalEndpoint);
Console.WriteLine("Waiting for a connection.....");
m:
clientSock = myList.AcceptSocket();
//clientSock.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReceiveTimeout,10000);
Console.WriteLine("Connection accepted from " + clientSock.RemoteEndPoint);
//byte[] b = new byte[100];
//int k = clientSock.Receive(b);
string fileName = "hello.wav";
NetworkStream networkStream = new NetworkStream(clientSock);
StreamReader sr = new StreamReader(networkStream);
//read file length
int length = int.Parse(sr.ReadLine());
if (networkStream.CanRead)
{
BinaryWriter bWrite = new BinaryWriter(File.Open(receivedPath + fileName, FileMode.Create));
int receivedBytesLen = -1;
byte[] clientData = new byte[4096 * 5000];
receivedBytesLen = networkStream.Read(clientData, 0, clientData.Length);
bWrite.Write(clientData, 0, receivedBytesLen);
do
{
receivedBytesLen = networkStream.Read(clientData, 0,clientData .Length);
bWrite.Write(clientData, 0, receivedBytesLen);
} while (receivedBytesLen > 0);
bWrite.Close();
networkStream.Close();
}
Console.WriteLine("Client:{0} connected & File {1} started received.", clientSock.RemoteEndPoint, fileName);
Console.WriteLine("File: {0} received & saved at path: {1}", fileName, receivedPath);
Recognizer_2 recognizeVoice = new Recognizer_2(clientSock);
recognizeVoice.recognize_wav(); // Acknowledgement
Console.WriteLine("\nResult Sent to the Client");
goto m;
}
Java Client:
Socket socket = new Socket("192.168.1.131", 5600);
BufferedReader response_Stream = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
File f = new File(mFileName);
byte[] buffer = new byte[(int) f.length()];
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(buffer, 0, buffer.length);
OutputStream outputStream = socket.getOutputStream();
outputStream.write(buffer);
outputStream.flush();
String final_Result_String = "";
if (response_Stream != null) {
String respose_text = "";
while ((respose_text = response_Stream.readLine()) != null) {
final_Result_String += respose_text;
}
}
Toast.makeText(getApplicationContext(), final_Result_String, 1)
.show();
outputStream.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
There is no dependance between the languages used by the server or the client.
Just the structure of the data is important !
You should search for some tutorials on socket programming with C#.
For example: http://www.codeproject.com/Articles/10649/An-Introduction-to-Socket-Programming-in-NET-using
But the language doesn't matter, understand how the data is formatted when sent on the network.
Edit: you should add a byte or two in the data indicating the length of it. It's not because you dont have data to read once that all the data has been received.
I have an image in my server which I want to send to my Java client through sockets. In c# I converted to byte array and then tried to send over the socket. But, a byte array in C# is unsigned so I tried to send signed byte array sbyte[] but it cannot be send by clientSocket.Send() method. On the java client side, I need to convert the byte array received to an Image object. Here is the exception trace that I get, at Image image = reader.read(0, param). Please help me with this.
Exception in thread "main" javax.imageio.IIOException: Bogus marker length
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readImageHeader(Native Method)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readNativeHeader(Unknown Source)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.checkTablesOnly(Unknown Source)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.gotoImage(Unknown Source)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readHeader(Unknown Source)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(Unknown Source)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(Unknown Source)
at ServerByteStreamWithoutOIS.main(ServerByteStreamWithoutOIS.java:54)
Here is my C# server code:
class Program
{
static void Main(String[] args)
{
Socket sListen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 2. Fill IP
IPAddress IP = IPAddress.Parse("147.174.117.187");
IPEndPoint IPE = new IPEndPoint(IP, 20229);
// 3. binding
sListen.Bind(IPE);
// 4. Monitor
Console.WriteLine("Service is listening ...");
sListen.Listen(2);
// 5. loop to accept client connection requests
while (true)
{
Socket clientSocket;
try
{
clientSocket = sListen.Accept();
}
catch
{
throw;
}
// send the file
byte[] buffer = ReadImageFile("1.jpg");
clientSocket.Send(buffer, buffer.Length, SocketFlags.None);
clientSocket.Close();
Console.WriteLine("Send success!");
}
}
private static byte[] ReadImageFile(String img)
{
FileInfo fileInfo = new FileInfo(img);
byte[] buf = new byte[fileInfo.Length];
FileStream fs = new FileStream(img, FileMode.Open, FileAccess.Read);
fs.Read(buf, 0, buf.Length);
fs.Close();
//fileInfo.Delete ();
GC.ReRegisterForFinalize(fileInfo);
GC.ReRegisterForFinalize(fs);
return buf;
}
}
}
Here is my Java client:
public class ServerByteStreamWithoutOIS {
public static void main(String[] args) throws IOException, ClassNotFoundException{
int port = 20229;
Socket sock = null;
InetAddress addr = null;
addr = InetAddress.getByName("147.174.117.187");
sock = new Socket(addr, port);
System.out.println("created socket!");
int count = 0;
while(true){
String line = "";
String realLine = "";
BufferedReader bReader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
byte[] buffer = null;
while((line=bReader.readLine() )!=null){
realLine = realLine + line;
System.out.println(line.getBytes());
}
buffer = realLine.getBytes();
//buffer = (byte[])ois.readObject();
ByteArrayInputStream bis = new ByteArrayInputStream(buffer);
Iterator<?> readers = ImageIO.getImageReadersByFormatName("jpg");
ImageReader reader = (ImageReader) readers.next();
Object source = bis; // File or InputStream, it seems file is OK
ImageInputStream iis = ImageIO.createImageInputStream(source);
//Returns an ImageInputStream that will take its input from the given Object
reader.setInput(iis, true);
ImageReadParam param = reader.getDefaultReadParam();
Image image = reader.read(0, param);
//got an image file
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
//bufferedImage is the RenderedImage to be written
Graphics2D g2 = bufferedImage.createGraphics();
g2.drawImage(image, null, null);
File imageFile = new File("image.bmp");
ImageIO.write(bufferedImage, "bmp", imageFile);
System.out.println(imageFile.getPath());
//Thread.sleep(100);
System.out.println("Done saving");
}
}
}
I believe the error is because you are converting the bytes received in the Java server to a string representation. This can result in an error because a jpg is binary data, and when some binary data can not be converted to a character in a string, some conversion occurs which will result in an error when you use the getBytes() function.
If you instead read the bytes from the inputstream using the read(byte[],int,int]) function, I think you should be alright.
http://download.oracle.com/javase/1.5.0/docs/api/java/io/InputStream.html#read(byte[], int, int)
Edit, added a working code example
The "problem" of Java having signed bytes is a non issue. In binary they are the same bits, so when written to a file, the same bits are written since they are still the same order.
I wrote an example of a C# client and a Java server that I got working. I'm sure you can find it of use.
Server – Java
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ImageServer {
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(8000);
Socket accept = server.accept();
InputStream inputStream = accept.getInputStream();
BufferedInputStream stream = new BufferedInputStream(inputStream);
int length = readInt(inputStream);
byte[] buf = new byte[length];
for (int read = 0; read < length; ) {
read += stream.read(buf, read, buf.length - read);
}
stream.close();
FileOutputStream fos = new FileOutputStream("image.png");
fos.write(buf, 0, buf.length);
fos.flush();
fos.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
private static int readInt(InputStream inputStream) throws IOException {
byte[] buf = new byte[4];
for (int read = 0; read < 4; ) {
read += inputStream.read(buf, 0, 4);
}
return toInt(buf);
}
public static int toInt(byte[] b) {
return (b[0] << 24)
+ ((b[1] & 0xFF) << 16)
+ ((b[2] & 0xFF) << 8)
+ (b[3] & 0xFF);
}
}
Client – C#
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace Test.SendImageClient {
public class Program {
public static void Main(string[] args) {
if (args.Length == 0) {
Console.WriteLine("usage: client imagefile");
return;
}
FileStream stream = File.OpenRead(args[0]);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect("localhost", 8000);
int length = IPAddress.HostToNetworkOrder((int)stream.Length);
socket.Send(BitConverter.GetBytes(length), SocketFlags.None);
byte[] buffer = new byte[1024];
int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) {
socket.Send(buffer, 0, read, SocketFlags.None);
}
socket.Close();
}
}
}
it seems like the bytes being received are not lining up w/the jpeg specification (can't be deserialized properly). are you sure the file on the server exists and that the c# byte[] is getting filled properly? maybe try to write the file on the server before sending it through the socket to ensure that you are actually reading a valid jpeg on the server.