java通过socket向android发送数据

java服务器端:

package kyq;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import com.sun.xml.internal.bind.util.Which;

public class KyqSever {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		try {
			
			ServerSocket severSocket = new ServerSocket(8888);
			
			while (true) {
				System.out.println("正在监听客户端的连接");
				Socket socket = severSocket.accept();
				SeverThread severThread = new SeverThread(socket);
				Thread thread = new Thread(severThread);
				thread.start();
				
			}
			
			
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}


package kyq;
import java.awt.image.BufferedImage;
import java.io.*;

import java.net.InetAddress;
import java.net.Socket;

import javax.imageio.ImageIO;

import com.sun.prism.Image;




/**
 * @author Administrator
 *
 */
public class SeverThread implements Runnable{

	Socket socket;
	BufferedOutputStream bos;
	BufferedInputStream bis;
	BufferedReader br;
	BufferedWriter bw;
	String path  = "img\\image16.png";
	
	public SeverThread(Socket socket) {
		super();
		this.socket = socket;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		
		try {
			InetAddress address = socket.getInetAddress();
			System.out.println("客户端ip地址"+address.getHostAddress());

			//bf = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			bos = new BufferedOutputStream(socket.getOutputStream());
			bis = new BufferedInputStream(socket.getInputStream());
			br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
//			bi = ImageIO.read(ImageIO.createImageInputStream(socket.))
			String str;
			System.out.println("等待接收消息");
			str = br.readLine();
			System.out.println("接收到消息");
			
			while (str!=null) {

				System.out.println("接收到消息未截断:"+str);
				str = str.substring(2);
				
				String command = str.substring(0,str.indexOf("##"));
				System.out.println("解析命令之后的"+str);
				
				str = str.substring(str.indexOf("##")+2);
				String username = str.substring(0,str.indexOf("##"));
				System.out.println("解析名字之后的"+str);
				
				str = str.substring(str.indexOf("##")+2);
				String pwd = str.substring(0,str.indexOf("##"));
				System.out.println("解析密码之后的"+str);
				
				
				System.out.println("username:"+username);
				System.out.println(" pwd:"+pwd);
				System.out.println(" com:"+command);
				if(username.equals("admin")&&pwd.equals("123456"))
				{
					bw.write("login");;//告诉客户端登录成功
					bw.write('\n');
//					bw.("login");
					bw.flush();
					
					FileInputStream fis = new FileInputStream("img\\image16.png");
					byte[] buf = new byte[1024];
					int len = 0;
					int i = 1;
					Thread.sleep(1000);//保证上面发送的login已经被android读取到,防止读取login时,清空下面的图片数据
					while((len = fis.read(buf))!=-1)
					{
						
						System.out.println("图片发送一次"+(i++)+"次"+len);
						bos.write(buf, 0, len);
					}
					bos.flush();
					System.out.println("图片发送完成"+username);
//					int bufferSize = 8192;
//					byte[] buf = new byte[bufferSize];
//					 DataInputStream fis = new DataInputStream(
//							 new BufferedInputStream(
//									 new FileInputStream(path)));
//					
//						int read = 0;
//						if(fis!=null)
//						{
//							read = fis.read(buf);
//						}
//						if(read == -1)
//						{
//							break;
//						}
//						dos.write(buf, 0, read);
//					
//					
//					
//					dos.flush();
//
//					System.out.println("文件传输完成"+ new File(path).length());
//					str = dis.readUTF();
//				
//					
//					
//				}else {
//					dos.writeUTF("login_no");
//					dos.flush();
//				}

				break;
				}
				
			}
		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		
	}

	
}

安卓端:

package com.rzg.kyq.Network;

import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

/**
 * Created by Administrator on 2021/5/3.
 */

public class BaseThread extends Thread {
    protected Socket socket;
//    protected DataOutputStream dos;
//    protected DataInputStream din;
    protected BufferedInputStream bis;
    protected BufferedOutputStream bos;
    @Override
    public void run() {
        super.run();
        try {
            socket = new Socket("10.0.2.2", 8888);
            // socket = new Socket("192.168.1.1",8888);
            Log.d("网络", "连接服务器成功!!:" + socket.getInetAddress().getHostAddress().toString());
//            dos = new DataOutputStream(socket.getOutputStream());
//            din =new DataInputStream(socket.getInputStream());
            bis = new BufferedInputStream(socket.getInputStream());






        } catch (IOException e) {
            Log.d("", "服务器连接失败!!!" + e.toString());
            e.printStackTrace();
        }


    }
   /* public  void Close()
    {
        try {
            if(din!=null)
            {
                din.close();
            }
            if(dos!=null)
            {
                dos.close();
            }
            if(socket!=null)
            {
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }*/
}

package com.rzg.kyq.Network;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.rzg.kyq.MainActivity;
import com.rzg.kyq.MyApplication;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.Socket;

/**
 * Created by Administrator on 2021/5/2.
 */

public class LoginThread extends BaseThread {
    String message;
    Handler handler;
    String username;
    String pwd;
    public static Bitmap bitmap;

    public LoginThread(String username, String pwd, Handler handler) {
        this.message = "##" + "login" + "##" + username + "##" + pwd + "##";
        this.username = username;
        this.pwd = pwd;
        this.handler = handler;
    }

    @Override
    public void run() {
        super.run();
        try {

            Log.d("网络", "向服务端发送信息" + message);
           // Reader reader = new Reader()
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            bw.write(message);
            bw.write('\n');
            bw.flush();
            String returnStr = br.readLine();
            Log.d("网络", "服务端回传消息" + returnStr);



//            byte[] buf = new byte[1024];
//            int len = 0;
//            while ((len = bis.read())!=-1)
//            {
//
//
//            }
            if ("login".equals(returnStr)) {


                /*
                * 接收图片*/

                bitmap = BitmapFactory.decodeStream(socket.getInputStream());
                Log.d("网络","图片接收完成"+bitmap.getHeight());
                /* */
                // din.readUTF()
                Bundle bundle = new Bundle();
                bundle.putString("username", username);

                Message message = Message.obtain();
                message.what = 1;
                message.setData(bundle);


                handler.sendMessage(message);

            } else if ("login_no".equals(returnStr)) {
                Bundle bundle = new Bundle();
                bundle.putString("username", username);
                Message message = Message.obtain();
                message.what = 2;
                message.setData(bundle);
                handler.sendMessage(message);

            }

           //父类中关闭方法


        } catch (IOException e) {
            Log.d("网络","一场");
            e.printStackTrace();
        }

    /*
    * 自定义的网络协议 :  ##命令## 参数 ## 参数 ##
    * */
    }
}


你可能感兴趣的:(Android,java,android,服务器)