要实现聊天当然要有一个服务端和客户端,服务端的作用是接收客户端的数据,再广播给所有客户端,这样就实现的了一个简单的聊天室。
一、服务端的实现
服务端选择在PC端用Eclipse建立项目。首先创建一个线程,在线程中创建ServerSocket用来监听客户端接入,每增加一个接入者,新开一个线程。
public class SocketListener extends Thread {
@Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(8888, 50);
Socket socket;
ChatSocket cs;
while (true) {
socket = serverSocket.accept();
cs = new ChatSocket(socket);
cs.start();
ChatManager.getChatManager().add(cs);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
然后在新开的线程中实现数据的接收和发送。
public class ChatSocket extends Thread{
private Socket socket;
public ChatSocket(Socket socket) {
this.socket = socket;
}
public void output(String s) {
try {
String msg;
int begin = s.indexOf("<");
int end = s.indexOf(">");
if (begin > -1 && end > -1) {
String name = s.substring(begin, end + 1);
s = s.substring(end + 1);
String time = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
msg = name + " " + time + "\n" + s + "\n";
} else {
msg = "请使用标准客户端连接\n";
}
socket.getOutputStream().write(msg.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
BufferedReader br;
String line;
try {
br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
line = null;
while ((line=br.readLine()) != null) {
ChatManager.getChatManager().publish(line);
}
br.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
然后,新建一个类,用来存放已连接客户端,实现数据广播。
public class ChatManager {
public static final String END_MSG_SYMBOL = "@$end$@";
private String msg = "";
private ChatManager() {}
private static final ChatManager cm = new ChatManager();
public static ChatManager getChatManager() {
return cm;
}
Vector<ChatSocket> vector = new Vector<ChatSocket>();
public void add(ChatSocket cs) {
vector.add(cs);
}
public void publish(String s) {
msg += s + "\n";
if(s.equals(END_MSG_SYMBOL)) {
for (ChatSocket cs : vector) {
cs.output(msg);
}
msg = "";
}
}
}
最后在主方法中开启服务,服务端就建立好了。
public class Main {
public static void main(String[] args) {
new SocketListener().start();
}
}
客户端选择在Android端。主要代码集中在发送和接收。
布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/tvCurrentName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/current_name"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/tvConnectState"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/connect_state"
android:textAppearance="?android:attr/textAppearanceMedium" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/etSetName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="@string/name" />
<Button
android:id="@+id/btnSetName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/set" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/etIP"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="27"
android:hint="@string/input_ip" />
<EditText
android:id="@+id/etPort"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="10"
android:hint="@string/port"
android:inputType="number" />
<Button
android:id="@+id/btnConnect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/connect" />
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/chat_record"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<TextView
android:id="@+id/tvChatRecord"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
<EditText
android:id="@+id/etMassage"
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="top"
android:hint="@string/message" />
<Button
android:id="@+id/btnSend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/send" />
</LinearLayout>
JAVA代码:
public class MainActivity extends Activity implements View.OnClickListener{
private EditText etIP, etPort, etMassage, etSetName;
private TextView tvChatRecord, tvCurrentName, tvConnectState;
private BufferedWriter writer;
private BufferedReader reader;
private Socket socket;
private SocketAddress socketAddress;
private boolean isConnected = false;
private SharedPreferences sp;
public static final String KEY = "key";
public static final String END_MSG_SYMBOL = "@$end$@";
private String currentName = null;
private boolean connectFailed = false;
private ProgressDialog progressDialog;
private AsyncTask<Void, String, Void> task;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
findViewById(R.id.btnConnect).setOnClickListener(this);
findViewById(R.id.btnSend).setOnClickListener(this);
findViewById(R.id.btnSetName).setOnClickListener(this);
}
private void init() {
etIP = (EditText) findViewById(R.id.etIP);
etPort = (EditText) findViewById(R.id.etPort);
etMassage = (EditText) findViewById(R.id.etMassage);
etSetName = (EditText) findViewById(R.id.etSetName);
tvChatRecord = (TextView) findViewById(R.id.tvChatRecord);
tvCurrentName = (TextView) findViewById(R.id.tvCurrentName);
tvConnectState = (TextView) findViewById(R.id.tvConnectState);
tvConnectState.setText("连接状态:未连接");
sp = getPreferences(Activity.MODE_PRIVATE);
currentName = sp.getString(KEY, null);
if (currentName != null) {
tvCurrentName.setText("当前昵称:" + currentName);
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnConnect:
if (currentName != null) {
connect();
} else {
Toast.makeText(this, "请先设置昵称后重新连接", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btnSend:
send();
break;
case R.id.btnSetName:
String tmp = etSetName.getText().toString().trim();
setName(tmp);
break;
}
}
private void setName(String s) {
if (!s.equals("")) {
SharedPreferences.Editor editor = sp.edit();
editor.putString(KEY, s);
if (editor.commit()) {
tvCurrentName.setText("当前昵称:" + s);
currentName = s;
etSetName.setText("");
Toast.makeText(this, "昵称设置成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "昵称设置失败,请重试", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "昵称不能为空", Toast.LENGTH_SHORT).show();
}
}
private void send() {
if (isConnected) {
try {
String msg = "<" + currentName + ">" + etMassage.getText().toString() + "\n" + END_MSG_SYMBOL + "\n";
writer.write(msg);
writer.flush();
etMassage.setText("");
} catch (IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(this, "未连接", Toast.LENGTH_SHORT).show();
}
}
private void connect() {
try {
if (writer != null) {
writer.close();
}
if (reader != null) {
reader.close();
}
if (socket != null && !socket.isClosed()) {
socket.close();
}
if (task != null && task.getStatus() != AsyncTask.Status.FINISHED) {
task.cancel(true);
}
} catch (IOException e) {
e.printStackTrace();
}
progressDialog = ProgressDialog.show(this, null, "正在连接...");
final String ip = etIP.getText().toString();
final int port = Integer.valueOf(etPort.getText().toString());
task = new AsyncTask<Void, String, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
socket = new Socket();
socketAddress = new InetSocketAddress(ip, port);
socket.connect(socketAddress, 5000);
publishProgress("connected");
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
isConnected = true;
String line;
while ((line = reader.readLine()) != null) {
if (isCancelled()) break;
publishProgress(line);
}
} catch (IOException e) {
connectFailed = true;
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
if (connectFailed) {
isConnected = false;
tvConnectState.setText("连接状态:未连接");
Toast.makeText(MainActivity.this, "连接失败,请重新连接", Toast.LENGTH_SHORT).show();
}
super.onPostExecute(aVoid);
}
@Override
protected void onProgressUpdate(String... values) {
if (isCancelled()) return;
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
if (values[0].equals("connected")) {
tvConnectState.setText("连接状态:已连接");
Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
} else {
if (!values[0].equals(END_MSG_SYMBOL)) {
tvChatRecord.append(values[0] + "\n");
}
}
super.onProgressUpdate(values);
}
}.execute();
}
}
manifest里加网络权限
<uses-permission android:name="android.permission.INTERNET" />
值得注意的是因为使用readline();方法,所以每条数据发送时都要加上换行符"\n"或"\r"之类,这个问题搞了我几个小时的时间,奶奶的。
还有,使用socket直接
socket = new Socket(ip, port);
一个对象出来时,如果IP不对,或者服务器没开等的情况时,会出现长时间没反应,不是无响应,也不报错。所以最
好还是加个超时的好。
当屏幕旋转,切换输入法键盘...一些会重新加载onCreate()方法时,程序会出问题。所以在manifest里配置一下,在Activity里加上下面一条
android:configChanges="keyboardHidden|orientation|screenSize|keyboard"