* 思想:
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", 9898)
//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 {public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(9898) // 服务器端端口
System.out.println("服务启动........................")
boolean flag = true // 定义标记,可以一直死循环
while (flag) { // 通过标记判断循环
new Thread(new ServerThreadUtil(server.accept())).start() // 启动线程
}
server.close() // 关闭服务器
}
}
public class ServerThreadUtil implements Runnable {
private static final String DIRPATH = "D:" + File.separator + "myfile"
+ File.separator // 目录路径
private Socket client = null
private UploadFile upload = null
public ServerThreadUtil(Socket client) {
this.client = client
System.out.println("新的客户端连接...")
}
@Override
public void run() {
try {
ObjectInputStream ois = new ObjectInputStream(
client.getInputStream()) // 反序列化
this.upload = (UploadFile) ois.readObject() // 读取对象//UploadFile需要和客户端传递过来的包名类名相同,如果不同则会报异常
System.out.println("文件标题:" + this.upload.getTitle())
System.out.println("文件类型:" + this.upload.getMimeType())
System.out.println("文件大小:" + this.upload.getContentLength())
PrintStream out = new PrintStream(this.client.getOutputStream())// BufferedWriter
out.print(this.saveFile())//返回响应
// BufferedWriter writer = null
// writer.write("")
} catch (Exception e) {
e.printStackTrace()
} finally {
try {
this.client.close()
} catch (IOException e) {
e.printStackTrace()
}
}
}
private boolean saveFile() throws Exception { // 负责文件内容的保存
/**
* java.util.UUID.randomUUID():
* UUID.randomUUID().toString()是javaJDK提供的一个自动生成主键的方法。 UUID(Universally
* Unique Identifier)全局唯一标识符,是指在一台机器上生成的数字,它保证对在同一时空中的所有机器都是唯一的,
* 是由一个十六位的数字组成
* ,表现出来的形式。由以下几部分的组合:当前日期和时间(UUID的第一个部分与时间有关,如果你在生成一个UUID之后,
* 过几秒又生成一个UUID,
* 则第一个部分不同,其余相同),时钟序列,全局唯一的IEEE机器识别号(如果有网卡,从网卡获得,没有网卡以其他方式获得
* ),UUID的唯一缺陷在于生成的结果串会比较长,字符串长度为36。
*
* UUID.randomUUID().toString()是java JDK提供的一个自动生成主键的方法。 UUID(Universally
* Unique Identifier)全局唯一标识符, 是指在一台机器上生成的数字,它保证对在同一时空中的所有机器都是唯一的,
* 是由一个十六位的数字组成,表现出来的形式
*/
File file = new File(DIRPATH + UUID.randomUUID() + "."
+ this.upload.getExt())
if (!file.getParentFile().exists()) {
file.getParentFile().mkdir()
}
OutputStream output = null
try {
output = new FileOutputStream(file)
output.write(this.upload.getContentData())
return true
} catch (Exception e) {
throw e
} finally {
output.close()
}
}
}
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
}
}
这个图片源码一般是看不在的,在网站上用的一般就jpeg和GIF的图片,你所说的图片源码不知道是不是photoshop等做图时的源文件(没有合并图层的)吧?这个一般是没有的。如果有你有办法的话不要忘记说一声啊,601621633@QQ.com欢迎分享,转载请注明来源:夏雨云
评论列表(0条)