双向通信 java 套接字与 android

Two way communication java socket with android

主服务器class

import java.awt.EventQueue;

import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JButton;

import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.net.ServerSocket;

import javax.swing.JScrollPane;
import javax.swing.JList;
import javax.swing.JPanel;

public class Serwer {

private JFrame frame;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Serwer window = new Serwer();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */

MyServer server;
Logowanie log;

public Serwer() {
    initialize();
}

public static DefaultListModel login1 = new DefaultListModel();
public static DefaultListModel haslo1 = new DefaultListModel();

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 405, 199);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   


    JButton start = new JButton("Start");
    start.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                server = new MyServer(login1, haslo1);
                log = new Logowanie(login1, haslo1);
            } catch (IOException e) {
                e.printStackTrace();
            }           
            server.start();
            log.start();

        }
    });
    frame.getContentPane().add(start, BorderLayout.WEST);

    JButton stop = new JButton("Stop");
    stop.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            if(server!=null){
                server.stopserver();
                server.stop();
                log.stopserver();
                log.stop();
                haslo1.addElement(login1.size());
                haslo1.addElement(login1.get(0));
            }
        }
    });
    frame.getContentPane().add(stop, BorderLayout.EAST);

    JPanel panel = new JPanel();
    frame.getContentPane().add(panel, BorderLayout.CENTER);
    panel.setLayout(null);

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBounds(10, 11, 124, 139);
    panel.add(scrollPane);

    JList login = new JList(login1);
    scrollPane.setViewportView(login);

    JScrollPane scrollPane_1 = new JScrollPane();
    scrollPane_1.setBounds(143, 11, 124, 139);
    panel.add(scrollPane_1);

    JList haslo = new JList(haslo1);
    scrollPane_1.setViewportView(haslo);
}
}

服务器记录线程

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.DefaultListModel;

public class Logowanie extends Thread {

    DefaultListModel login, pass;
    String log;
    ServerSocket serversocket;
    Socket socket;

    public Logowanie(DefaultListModel log, DefaultListModel pas) throws UnknownHostException, IOException{
        login = log;
        pass = pas;
        serversocket = new ServerSocket(1235, 50, InetAddress.getByName("0.0.0.0"));
    }

    public void run(){
        for(;;){
            try{
            while(true){
            socket = serversocket.accept();
            login.addElement("Logowanie");

            BufferedReader in  = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            log = in.readLine();
            in.close();

            for(int i = 0; i < login.size();i++){
                if(login.get(i).toString().equals(log)){
                    PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
                    out.print(login.get(i).toString()+"|"+pass.get(i).toString());
                    out.close();
                    socket.close();
                    break;
                }
            }
            }
            }
            catch(Exception e){
                login.addElement(e.getMessage());
            }
        }
    }

    public void stopserver(){
        try{
            serversocket.close();
        }
        catch(IOException e){
            login.addElement(e.getMessage());
        }

    }
}

客户端 (Android) 记录 AsyncTask

package okar.graandro;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

import android.app.Activity;
import android.content.Intent;
import android.location.GpsStatus.Listener;
import android.os.AsyncTask;
import android.widget.EditText;

public class Logowanie extends AsyncTask<Object, Void, String> {

    EditText text;
    EditText pass;
    String msg;
    int rozz;
    Activity act;

    public Logowanie(Activity myContext){
        act = myContext;
        text = (EditText) myContext.findViewById(R.id.login);
        pass = (EditText) myContext.findViewById(R.id.haslo);
    }

    @Override
    protected String doInBackground(Object... params) {
        try{
            Socket socket = new Socket(InetAddress.getByName("192.168.1.1"), 1235);
            PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
            out.print(text);
            out.close();

            this.wait(1000);

            BufferedReader in  = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            msg = in.readLine();
            in.close();
            socket.close();

            for(int i = 0; i < msg.length(); i++){
                if(msg.substring(i, i+1).equals("|")){
                    rozz = i;
                }
            }


        }
        catch( Exception e){
             msg = e.getMessage();
        }

        if(msg.substring(0,rozz).equals(text.getText().toString()) && msg.substring(rozz+1,msg.length()).equals(pass.getText().toString())){
            return "1";
        }else{
            return "0";
        }

    }

    @Override
    protected void onPostExecute(String msg) {
        if(Integer.valueOf(msg) == 1){
            Intent intent = new Intent(act, Mapa.class);
            act.startActivity(intent);
        }else{
            text.setText("niepoprawne dane");
        }

    }

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected void onProgressUpdate(Void... values) {
    }
}

我对这段代码有疑问。难道我做错了什么?我应该等待还是检查线程或 AsyncTask 中的状态?

当我尝试使用它登录时,我收到消息 "Socket is closed"。

我不知道我能用它做什么。

问候。

编辑

02-11 21:24:57.505: E/AndroidRuntime(1159): FATAL EXCEPTION: AsyncTask #1
02-11 21:24:57.505: E/AndroidRuntime(1159): java.lang.RuntimeException: An error occured while executing doInBackground()
02-11 21:24:57.505: E/AndroidRuntime(1159):     at android.os.AsyncTask.done(AsyncTask.java:299)
02-11 21:24:57.505: E/AndroidRuntime(1159):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
02-11 21:24:57.505: E/AndroidRuntime(1159):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
02-11 21:24:57.505: E/AndroidRuntime(1159):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
02-11 21:24:57.505: E/AndroidRuntime(1159):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
02-11 21:24:57.505: E/AndroidRuntime(1159):     at android.os.AsyncTask$SerialExecutor.run(AsyncTask.java:230)
02-11 21:24:57.505: E/AndroidRuntime(1159):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
02-11 21:24:57.505: E/AndroidRuntime(1159):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
02-11 21:24:57.505: E/AndroidRuntime(1159):     at java.lang.Thread.run(Thread.java:856)
02-11 21:24:57.505: E/AndroidRuntime(1159): Caused by: java.lang.NullPointerException
02-11 21:24:57.505: E/AndroidRuntime(1159):     at okar.graandro.Logowanie.doInBackground(Logowanie.java:56)
02-11 21:24:57.505: E/AndroidRuntime(1159):     at okar.graandro.Logowanie.doInBackground(Logowanie.java:1)
02-11 21:24:57.505: E/AndroidRuntime(1159):     at android.os.AsyncTask.call(AsyncTask.java:287)
02-11 21:24:57.505: E/AndroidRuntime(1159):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)

您正在客户端的 doItBackground() 方法中关闭 OutputStream:

        PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
        out.print(text);
        out.close();

并且关闭 InputStream 或 OutputStream 会关闭套接字,参见:

Socket.getInputStream():

关闭返回的 InputStream 将关闭关联的套接字。

我认为您必须使用 shutdownInput() / shutdownOutput() 方法。