我已经编写了一个基于套接字的Android到服务器应用程序来发送图像。以下是我迄今为止取得的成功:套接字正在连接,图像正在发送,但就是这样。它仍然被发送,我在服务器端看到0kb的文件,发送永远不会结束。
我在其上发送了一张233kb的JPEG图像。
这是客户端:
public class AccountCreator extends Activity {
private String serverIpAddress = "10.0.2.2";
private boolean connected = false;
private Handler handler = new Handler();
private Socket socket;
private Button sendimage;
//private ImageView profile;
private byte [] imgbyte;
String filepath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mes_registerpage);
sendimage = (Button) findViewById(R.id.sendpic);
ImageView imv = (ImageView)findViewById(R.id.imageView1);
sendimage.setOnClickListener(connectListener);
filepath = "storage/sdcard/autumn.jpg";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
fis = new FileInputStream(imagefile);
} catch (FileNotFoundException e) {
System.out.println("file not found");
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
imgbyte = getBytesFromBitmap(bm);
imv.setImageBitmap(bm);
}
private OnClickListener connectListener = new OnClickListener() {
@Override
public void onClick(View v) {
if (!connected) {
// serverIpAddress = serverIp.getText().toString();
// if (!serverIpAddress.equals(""))
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
};
public class ClientThread implements Runnable {
public void run() {
try {
// InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
socket = new Socket(serverIpAddress,1500);
connected = true;
while (connected==true) {
try {
/*File myFile = new File (filepath);
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = socket.getOutputStream();
Log.d("ClientActivity", "C: Sending command.");
//System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();*/
Log.d("ClientActivity", "C: Sending command.");
/*PrintWriter out = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(socket
.getOutputStream())), true);*/
// WHERE YOU ISSUE THE COMMANDS
OutputStream output = socket.getOutputStream();
Log.d("ClientActivity", "C: image writing.");
output.write(imgbyte);
output.flush();
// out.println("Hey Server!");
Log.d("ClientActivity", "C: Sent.");
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
protected void onStop() {
super.onStop();
try {
// MAKE SURE YOU CLOSE THE SOCKET UPON EXITING
socket.close();
connected = false;
} catch (IOException e) {
e.printStackTrace();
}
}
public byte[] getBytesFromBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, stream);
return stream.toByteArray();
}
}
这是服务器代码:
public Server(int port) {
this(port, null);
}
public Server(int port, ServerGUI sg) {
this.sg = sg;
this.port = port;
sdf = new SimpleDateFormat("HH:mm:ss");
al = new ArrayList<ClientThread>();
}
public void start() throws InterruptedException {
keepGoing = true;
try
{
// the socket used by the server
ServerSocket serverSocket = new ServerSocket(port);
// infinite loop to wait for connections
while(keepGoing)
{
// format message saying we are waiting
display("Server waiting for Clients on port " + port +
".");
Socket socket = serverSocket.accept();
// if I was asked to stop
if(!keepGoing)
break;
ClientThread t = new ClientThread(socket);
jobdone=false;
al.add(t);
t.start();
}
// I was asked to stop
try {
serverSocket.close();
for(int i = 0; i < al.size(); ++i) {
ClientThread tc = al.get(i);
try {
tc.sInput.close();
tc.sOutput.close();
tc.socket.close();
}
catch(IOException ioE) {
// not much I can do
}
}
}
catch(Exception e) {
display("Exception closing the server and clients: " + e);
}
}
// something went bad
catch (IOException e) {
String msg = sdf.format(new Date()) + " Exception on new ServerSocket: " + e +
"\n";
display(msg);
}
}
/*
* For the GUI to stop the server
*/
protected void stop() {
keepGoing = false;
// connect to myself as Client to exit statement
// Socket socket = serverSocket.accept();
try {
new Socket("10.0.2.2",1500);
}
catch(Exception e) {
// nothing I can really do
}
}
/*
* Display an event (not a message) to the console or the GUI
*/
private void display(String msg) {
String time = sdf.format(new Date()) + " " + msg;
if(sg == null)
System.out.println(time);
else
sg.appendEvent(time + "\n");
}
// create a server object and start it
public static void shutdown() {
jobdone = true;
}
/** One instance of this thread will run for each client */
class ClientThread extends Thread {
// the socket where to listen/talk
String Type;
Socket socket;
InputStream sInput;
ObjectOutputStream sOutput;
// my unique id (easier for deconnection)
int id;
// Constructore
ClientThread(Socket socket) throws InterruptedException, IOException {
// a unique id
id = ++uniqueId;
this.socket = socket;
/* Creating both Data Stream */
System.out.println("Thread trying to create Object Input/Output
Streams");
// create output first
int bytesRead;
int current = 0;
int filesize=65383;
byte [] mybytearray2 = new byte [filesize];
try {
InputStream is = socket.getInputStream();
System.out.println("receiving");
FileOutputStream fos = new FileOutputStream("D://IMG-
20130112-WA0011.jpeg");
// destination path and name of file
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray2,0,mybytearray2.length);
current = bytesRead;
try {
bytesRead =
is.read(mybytearray2, current,
(mybytearray2.length-current));
if(bytesRead >= 0)
{current += bytesRead;
}
while(bytesRead > -1);
{
bos.write(mybytearray2, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
//System.out.println(end-start);
bos.close();
}
}finally{
}
}finally{
}
}
}
// what will run forever
// remove myself from the arrayList containing the list of the
// connected Clients
public void main(String[] args) throws InterruptedException {
// start server on port 1500 unless a PortNumber is specified
int portNumber = 1500;
switch(args.length) {
case 1:
try {
portNumber = Integer.parseInt(args[0]);
}
catch(Exception e) {
System.out.println("Invalid port number.");
System.out.println("Usage is: > java
Server [portNumber]");
return;
}
case 0:
break;
default:
System.out.println("Usage is: > java Server
[portNumber]");
return;
}
// create a server object and start it
Server server = new Server(portNumber);
server.start();
}
}
你们知道出了什么问题吗?
答案 0 :(得分:1)
int filesize=65383;
byte [] mybytearray2 = new byte [filesize];
你不能正确地知道文件大小。此外,你发送一个233kB的文件,并尝试读取mybytearray2中的所有文件将给你一个缓冲区溢出,你的服务器将崩溃。顺便说一句:你从哪里获得/复制这段代码?我以前见过它。我没有好处。