手机和PC之间的Android聊天

时间:2013-03-08 15:07:10

标签: android sockets chat inputstream outputstream

我在我的电脑上运行了一个简单的套接字服务器,我为个人电脑提供了一个客户端,但是我想让它适应Android,但它一直在崩溃,告诉我在closeChat()方法中出现了问题但是我无法弄清楚是什么。这是我的代码:

    package com.jister13.chattest;

import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class ChatRoom extends Activity
{
    String ip;

    EditText userText;
    EditText chatWindow;
    Button send;

    private ObjectOutputStream output;
    private ObjectInputStream input;
    private String message = "";
    private String serverIP;
    private Socket connection;

    private Handler handler;

    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Bundle extras = getIntent().getExtras();
        if(extras != null)
        {
            ip = extras.getString("IP");
            serverIP = ip;
        }
        setContentView(R.layout.chat_room);
        setRequestedOrientation(1);

        handler = new Handler();

        userText = (EditText) findViewById(R.id.editText_UserText);
        chatWindow = (EditText) findViewById(R.id.editText_ChatWindow);
        chatWindow.addTextChangedListener(new TextWatcher(){
            public void afterTextChanged(Editable s) {
            }
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Toast.makeText(ChatRoom.this, "Updated", Toast.LENGTH_LONG).show();
            }
        });
        send = (Button) findViewById(R.id.button_Send);
        send.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                sendMessage("You: " + userText.getText().toString() + "\n");
                userText.setText("");
            }
        });

        startRunning();
    }
    public void startRunning()
    {
        try{
            connectToServer();
            setupStreams();
            whileChatting();
        }catch(EOFException eofException){
            showMessage("\n Chat Session Closed");
        }catch(IOException ioException){
            ioException.printStackTrace();
        }finally{
            closeChat();
        }
    }
    private void connectToServer() throws IOException
    {
        showMessage("Starting Connection...");
        connection = new Socket(InetAddress.getByName(serverIP), 0511);
        showMessage("\n Connection Established: "+connection.getInetAddress().getHostName());
    }
    private void setupStreams() throws IOException
    {
        output = new ObjectOutputStream(connection.getOutputStream());
        output.flush();
        input = new ObjectInputStream(connection.getInputStream());
        showMessage("\n Chatting streams are now enabled...");
    }
    private void whileChatting() throws IOException 
    {
        ableToType(true);
        do{
            try{
                message = (String) input.readObject();
                showMessage("\n "+message);
            }catch(ClassNotFoundException classNotFoundException){
                showMessage("\n Some Error Occured");
            }
        }while(!message.equals("SERVER - END"));
    }
    private void closeChat()
    {
        showMessage("\n Closing Application...");
        ableToType(false);
        try{
            input.close();
            output.close();
            connection.close();
        }catch(IOException e){
            e.printStackTrace();
        }
    }
    private void sendMessage(String text)
    {
        try{
            output.writeObject("Else: "+text);
            output.flush();
            showMessage("You: "+text+"\n");
        }catch(IOException e){
            chatWindow.append("\n An Error Occured *See ChatRoom.java -> sendMessage()*");
        }
    }
    private void showMessage(final String message)
    {
        handler.post(new Runnable(){
            public void run(){
                chatWindow.append(message);
            }
        });
    }
    private void ableToType(final boolean TorF)
    {
        //userText.setEditable(TorF);
    }
}

http://www.mediafire.com/view/?hr441qalu6b6d7s这是错误缩小的图像。

继承整个PrintStackTrace:

03-08 11:02:43.595: E/AndroidRuntime(3959): FATAL EXCEPTION: main
03-08 11:02:43.595: E/AndroidRuntime(3959): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.jister13.chattest/com.jister13.chattest.ChatRoom}: java.lang.NullPointerException
03-08 11:02:43.595: E/AndroidRuntime(3959):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2088)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2113)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at android.app.ActivityThread.access$700(ActivityThread.java:139)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1224)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at android.os.Looper.loop(Looper.java:137)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at android.app.ActivityThread.main(ActivityThread.java:4918)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at java.lang.reflect.Method.invokeNative(Native Method)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at java.lang.reflect.Method.invoke(Method.java:511)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at dalvik.system.NativeStart.main(Native Method)
03-08 11:02:43.595: E/AndroidRuntime(3959): Caused by: java.lang.NullPointerException
03-08 11:02:43.595: E/AndroidRuntime(3959):     at com.jister13.chattest.ChatRoom.closeChat(ChatRoom.java:115)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at com.jister13.chattest.ChatRoom.startRunning(ChatRoom.java:82)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at com.jister13.chattest.ChatRoom.onCreate(ChatRoom.java:69)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at android.app.Activity.performCreate(Activity.java:5048)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2052)
03-08 11:02:43.595: E/AndroidRuntime(3959):     ... 11 more

1 个答案:

答案 0 :(得分:0)

简单地说,input为空。

运行时:

public void startRunning()
{
    try{
        connectToServer();
        setupStreams();
        whileChatting();
    }catch(EOFException eofException){
        showMessage("\n Chat Session Closed");
    }catch(IOException ioException){
        ioException.printStackTrace();
    }finally{
        closeChat();
    }
}

private void connectToServer() throws IOException
{
    showMessage("Starting Connection...");
    connection = new Socket(InetAddress.getByName(serverIP), 0511);
    showMessage("\n Connection Established: "+connection.getInetAddress().getHostName());
}

private void setupStreams() throws IOException
{
    output = new ObjectOutputStream(connection.getOutputStream());
    output.flush();
    input = new ObjectInputStream(connection.getInputStream());
    showMessage("\n Chatting streams are now enabled...");
}

如果您在input中分配setupStreams()之前的任何地方收到例外,那么当finally拨打closeChat()时,它将为空。由于你没有在那里检查null,它会翻转。

我的建议?在使用它们之前先检查一下:

private void closeChat()
{
    ...
    if(input != null)
        input.close();
    if(output != null)
        output.close();       
    if(connection != null)
        connection.close();
    ....
}