发布网友 发布时间:2022-04-25 05:23
共2个回答
热心网友 时间:2023-10-29 18:33
/**
* 思想:
1.直接将所有数据安装字节数组发送
2.对象序列化方式
*/
/**
* thread方式
*
* @author Administrator
*/
public class TestSocketActivity4 extends Activity {
private static final int FINISH = 0;
private Button send = null;
private TextView info = null;
private Handler myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case FINISH:
String result = msg.obj.toString(); // 取出数据
if ("true".equals(result)) {
TestSocketActivity4.this.info.setText("操作成功!");
} else {
TestSocketActivity4.this.info.setText("操作失败!");
}
break;
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_test_sokect_activity4);
// StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
// .detectDiskReads().detectDiskWrites().detectNetwork()
// .penaltyLog().build());
// StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
// .detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
// .penaltyLog().penaltyDeath().build());
this.send = (Button) super.findViewById(R.id.send);
this.info = (TextView) super.findViewById(R.id.info);
this.send.setOnClickListener(new SendOnClickListener());
}
private class SendOnClickListener implements OnClickListener {
@Override
public void onClick(View v) {
try {
new Thread(new Runnable() {
@Override
public void run() {
try {
//1:
Socket client = new Socket("192.168.1.165", 98);
//2:
ObjectOutputStream oos = new ObjectOutputStream(
client.getOutputStream());
//3:
UploadFile myFile = SendOnClickListener.this
.getUploadFile();
//4:
oos.writeObject(myFile);// 写文件对象
// oos.writeObject(null);// 避免EOFException
oos.close();
BufferedReader buf = new BufferedReader(
new InputStreamReader(client
.getInputStream())); // 读取返回的数据
String str = buf.readLine(); // 读取数据
Message msg = TestSocketActivity4.this.myHandler
.obtainMessage(FINISH, str);
TestSocketActivity4.this.myHandler.sendMessage(msg);
buf.close();
client.close();
} catch (Exception e) {
Log.i("UploadFile", e.getMessage());
}
}
}).start();
} catch (Exception e) {
e.printStackTrace();
}
}
private UploadFile getUploadFile() throws Exception { // 包装了传送数据
UploadFile myFile = new UploadFile();
myFile.setTitle("tangcco安卓之Socket的通信"); // 设置标题
myFile.setMimeType("image/png"); // 图片的类型
File file = new File(Environment.getExternalStorageDirectory()
.toString()
+ File.separator
+ "Pictures"
+ File.separator
+ "b.png");
InputStream input = null;
try {
input = new FileInputStream(file); // 从文件中读取
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte data[] = new byte[1024];
int len = 0;
while ((len = input.read(data)) != -1) {
bos.write(data, 0, len);
}
myFile.setContentData(bos.toByteArray());
myFile.setContentLength(file.length());
myFile.setExt("png");
} catch (Exception e) {
throw e;
} finally {
input.close();
}
return myFile;
}
}
}
public class UploadFile implements Serializable {
private String title;
private byte[] contentData;
private String mimeType;
private long contentLength;
private String ext;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public byte[] getContentData() {
return contentData;
}
public void setContentData(byte[] contentData) {
this.contentData = contentData;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public long getContentLength() {
return contentLength;
}
public void setContentLength(long contentLength) {
this.contentLength = contentLength;
}
public String getExt() {
return ext;
}
public void setExt(String ext) {
this.ext = ext;
}
}
下边是服务端
public class Main4 {热心网友 时间:2023-10-29 18:33
这是服务端代码
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server01 {
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(30000);
Socket socket = server.accept();
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
FileInputStream fis = new FileInputStream("C:/sunnyTest/picture/cat01.jpg");
int size = fis.available();
System.out.println("size = "+size);
byte[] data = new byte[size];
fis.read(data);
dos.writeInt(size);
dos.write(data);
dos.flush();
dos.close();
fis.close();
socket.close();
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这里是客户端代码
import com.login.R;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class TestActivity extends Activity {
private ImageView imageView = null;
private Bitmap bmp = null;
private ImageView imageView02;
private Bitmap bmp02;
private Button button02;
private String uploadFile="/mnt/sdcard/qt.png";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image);
imageView = (ImageView) findViewById(R.id.image01);
Button btn = (Button) findViewById(R.id.Button01);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Socket socket = null;
try {
socket = new Socket("192.168.1.203", 30000);
DataInputStream dataInput = new DataInputStream(socket.getInputStream());
int size = dataInput.readInt();
byte[] data = new byte[size];
int len = 0;
while (len < size) {
len += dataInput.read(data, len, size - len);
}
ByteArrayOutputStream outPut = new ByteArrayOutputStream();
bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
bmp.compress(CompressFormat.PNG, 100, outPut);
imageView.setImageBitmap(bmp);
//Bitmap bitmap = BitmapFactory.decodeStream(dataInput);
//myHandler.obtainMessage().sendToTarget();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
}
客户端向服务端发送图片的代码:
服务端:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class Server02 {
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(40000);
Socket socket = server.accept();
DataInputStream dos = new DataInputStream(socket.getInputStream());
int len = dos.available();
System.out.println("len = "+len);
byte[] data = new byte[len];
dos.read(data);
System.out.println("data = "+data);
dos.close();
socket.close();
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端:
private String url = "http://www.yszaixian.cn"
imageView02 = (ImageView)findViewById(R.id.image02);
button02 = (Button)findViewById(R.id.Button02);
button02.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
Socket socket;
try {
socket = new Socket("192.168.1.203",40000);
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.qt);
imageView02.setImageBitmap(bitmap);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//读取图片到ByteArrayOutputStream
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] bytes = baos.toByteArray();
out.write(bytes);
System.out.println("bytes--->"+bytes);
out.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}