我已经为一个简单的聊天应用程序做了一个 android 应用程序。我使用命令提示符作为服务器,聊天是用模拟器作为客户端完成的。当我们使用 WIFI 将 apk 放入手机时,这个应用程序不起作用。Android客户端程序如下图所示包edu.UTEP.android;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class AndyChatActivity extends Activity {
private Handler handler = new Handler();
public ListView msgView;
public ArrayAdapter<String> msgList;
// public ArrayAdapter<String> msgList=new ArrayAdapter<String>(this,
// android.R.layout.simple_list_item_1);;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
msgView = (ListView) findViewById(R.id.listView);
msgList = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1);
msgView.setAdapter(msgList);
// msgView.smoothScrollToPosition(msgList.getCount() - 1);
Button btnSend = (Button) findViewById(R.id.btn_Send);
receiveMsg();
btnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(AndyChatActivity.this, "here", Toast.LENGTH_SHORT).show();
final EditText txtEdit = (EditText) findViewById(R.id.txt_inputText);
String msg=txtEdit.getText().toString();
Toast.makeText(AndyChatActivity.this, msg, Toast.LENGTH_SHORT).show();
//msgList.add(txtEdit.getText().toString());
sendMessageToServer(txtEdit.getText().toString());
msgView.smoothScrollToPosition(msgList.getCount() - 1);
}
});
//receiveMsg();
//----------------------------
//server msg receieve
//-----------------------
//End Receive msg from server//
}
public void sendMessageToServer(String str) {
final String str1=str;
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
//String host = "https://www.tudens.in";
String host="192.168.1.5";
//Toast.makeText(AndyChatActivity.this, "thread Opened", Toast.LENGTH_SHORT).show();
//String host2 = "127.0.0.1";
PrintWriter out;
try {
Socket socket = new Socket(host, 8008);
out = new PrintWriter(socket.getOutputStream());
Log.d("1", "good");
// out.println("hello");
out.println(str1);
Log.d("2", "gd");
out.flush();
Log.d("", "hello");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("", "hello222");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("", "hello4333");
}
}
}).start();
}
public void receiveMsg()
{
new Thread(new Runnable()
{
@Override
public void run() {
// TODO Auto-generated method stub
final String host="192.168.1.5";
//final String host="10.0.2.2";
//final String host="localhost";
Socket socket = null ;
BufferedReader in = null;
try {
socket = new Socket(host,8008);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true)
{
String msg = null;
try {
msg = in.readLine();
Log.d("","MSGGG: "+ msg);
//msgList.add(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(msg == null)
{
break;
}
else
{
displayMsg(msg);
}
}
}
}).start();
}
public void displayMsg(String msg)
{
final String mssg=msg;
handler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
msgList.add(mssg);
msgView.setAdapter(msgList);
msgView.smoothScrollToPosition(msgList.getCount() - 1);
Log.d("","hi");
}
});
}
}
java服务器程序如下图所示:
import java.io.*;
import java.net.*;
import java.util.*;
/**
* A simple chat server implemented using TCP/IP sockets. A client can
* connect to this server and send messages to other clients. The chat
* server receives messages from clients and broadcast them to all the
* connected clients. A message is an arbitrary text and is also
* printed on stdout. The default port number is 8008.
*
* <pre>
* Usage: java ChatServer
* </pre>
*
* @author Yoonsik Cheon
*/
public class ChatServer {
private static final String USAGE = "Usage: java ChatServer";
/** Default port number on which this server to be run. */
private static final int PORT_NUMBER = 8008;
/** List of print writers associated with current clients,
* one for each. */
private List<PrintWriter> clients;
/** Creates a new server. */
public ChatServer() {
clients = new LinkedList<PrintWriter>();
}
/** Starts the server. */
public void start() {
System.out.println("AndyChat server started on port "
+ PORT_NUMBER + "!");
try {
ServerSocket s = new ServerSocket(PORT_NUMBER);
for (;;) {
Socket incoming = s.accept();
new ClientHandler(incoming).start();
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("AndyChat server stopped.");
}
/** Adds a new client identified by the given print writer. */
private void addClient(PrintWriter out) {
synchronized(clients) {
clients.add(out);
}
}
/** Adds the client with given print writer. */
private void removeClient(PrintWriter out) {
synchronized(clients) {
clients.remove(out);
}
}
/** Broadcasts the given text to all clients. */
private void broadcast(String msg) {
for (PrintWriter out: clients) {
out.println(msg);
out.flush();
}
}
public static void main(String[] args) {
if (args.length > 0) {
System.out.println(USAGE);
System.exit(-1);
}
new ChatServer().start();
}
/** A thread to serve a client. This class receive messages from a
* client and broadcasts them to all clients including the message
* sender. */
private class ClientHandler extends Thread {
/** Socket to read client messages. */
private Socket incoming;
/** Creates a hander to serve the client on the given socket. */
public ClientHandler(Socket incoming) {
this.incoming = incoming;
}
/** Starts receiving and broadcasting messages. */
public void run() {
PrintWriter out = null;
try {
out = new PrintWriter(
new OutputStreamWriter(incoming.getOutputStream()));
// inform the server of this new client
ChatServer.this.addClient(out);
out.print("Welcome to AndyChat! ");
out.println("Enter BYE to exit.");
out.flush();
BufferedReader in
= new BufferedReader(
new InputStreamReader(incoming.getInputStream()));
for (;;) {
String msg = in.readLine();
if (msg == null) {
break;
} else {
if (msg.trim().equals("BYE"))
break;
System.out.println("Received: " + msg);
// broadcast the receive message
ChatServer.this.broadcast(msg);
}
}
incoming.close();
ChatServer.this.removeClient(out);
} catch (Exception e) {
if (out != null) {
ChatServer.this.removeClient(out);
}
e.printStackTrace();
}
}
}
}