将我的TCP android应用程序转为jar

时间:2014-02-17 05:45:49

标签: java android

我已经构建了一个TCP服务器,现在我想把它变成一个jar,所以我可以在许多不同的应用程序中使用它。所以基本上以后我想把它包含在其他项目中。如果它只是一个功能列表,我可以弄明白,但它不是我所以我不确定。我想把它全部只做一个函数但它不会运行,当我调用该函数时应用程序就会失败。

此外,我希望其他人可以找到对自己的项目有用的服务器代码

public class MainActivity extends Activity {

 private ServerSocket serverSocket;
 Handler updateConversationHandler;
 Thread serverThread = null;
 public String serverIP = "127.0.0.1";
 private InetAddress serverAddr;
 public static final int SERVERPORT = 4444;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    updateConversationHandler = new Handler();
    this.serverThread = new Thread(new ServerThread());
    this.serverThread.start();

}

@Override
protected void onStop() {
    super.onStop();
    try {
        serverSocket.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

class ServerThread implements Runnable {

    public void run() {
        Socket socket = null;
        try {
            serverSocket = new ServerSocket(SERVERPORT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        while (!Thread.currentThread().isInterrupted()) {
            try {
                socket = serverSocket.accept();
                CommunicationThread commThread = new CommunicationThread(socket);
                new Thread(commThread).start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

class CommunicationThread implements Runnable {
    private Socket clientSocket;
    private BufferedReader input;
    public CommunicationThread(Socket clientSocket) {
        this.clientSocket = clientSocket;
        try {
            this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            try {
                String read = input.readLine();
                updateConversationHandler.post(new updateUIThread(read));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

0 个答案:

没有答案