Android基于socket的群聊程序

在网上看了好多,但是感觉不是太简单就是只能单独聊,所以就自己写了个可以群聊的,直接上代码了

一、服务器端

这里用的MyEclipse作为服务器端

MyServerScoket.java

package com.scme.server;

public class MyServerScoket {

    public static void main(String[] args) {
new ServerListener().start();
}
}

ServerListener.java

package com.scme.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket; import javax.swing.JOptionPane; public class ServerListener extends Thread { @Override
public void run() {
// 1-65535
try {
// 端口
ServerSocket serverScoket = new ServerSocket(12345);
while (true) {
// 阻塞当前线程
Socket socket = serverScoket.accept();
// 建立连接,控制台打印
System.out.println("有客户端连接到了本机的12345端口");
// 弹出窗口提示
JOptionPane.showMessageDialog(null, "有客户端连接到了本机的12345端口");
//将socket传递新的线程
ChatSocket cs = new ChatSocket(socket);
cs.start();
ChatManger.getChatManger().add(cs);
} } catch (IOException e) {
e.printStackTrace();
}
}
}

ChatSocket.java

package com.scme.server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket; public class ChatSocket extends Thread { Socket socket; public ChatSocket(Socket s){
this.socket = s;
} public void out(String out){
try {
socket.getOutputStream().write((out+"\n").getBytes("UTF-8"));
} catch (Exception e) {
e.printStackTrace();
} } @Override
public void run() {
out("你已经连接到本服务器了");
try {
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
ChatManger.getChatManger().publish(this, line);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
} }
}

ChatManger.java

package com.scme.server;

import java.util.Vector;

public class ChatManger {

    //单例化
private ChatManger(){}
private static final ChatManger cm = new ChatManger();
public static ChatManger getChatManger(){
return cm;
} Vector<ChatSocket> vector = new Vector<ChatSocket>(); public void add(ChatSocket cs){
vector.add(cs);
} public void publish(ChatSocket cs,String out){
for (int i = 0; i < vector.size(); i++) {
ChatSocket csChatSocket = vector.get(i);
if (!cs.equals(csChatSocket)) {
csChatSocket.out(out);
}
}
}
}

二、客户端

布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" > <LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" > <EditText
android:id="@+id/ip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.6"
android:hint="输入服务器的IP地址"
android:text="10.0.2.2" > </EditText> <Button
android:id="@+id/connect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.4"
android:text="连接" /> </LinearLayout> <ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.86" > <TextView
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="Ready..." />
</ScrollView> <EditText
android:id="@+id/edit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="在这里输入内容" /> <Button
android:id="@+id/send"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="发送" /> </LinearLayout>

Main.java

package com.scme.aserversocket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket; import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast; public class MainActivity extends Activity implements OnClickListener { private EditText ip,edit;
private TextView text; private void init() {
ip = (EditText) findViewById(R.id.ip);
edit = (EditText) findViewById(R.id.edit);
text = (TextView) findViewById(R.id.text);
findViewById(R.id.connect).setOnClickListener(this);
findViewById(R.id.send).setOnClickListener(this);
} @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
} Socket socket = null;
BufferedWriter writer = null;
BufferedReader reader = null; /**
* 连接
*/
public void connect(){
AsyncTask<Void, String, Void> read = new AsyncTask<Void, String, Void>(){ @Override
protected Void doInBackground(Void... params) {
try {
socket = new Socket(ip.getText().toString(), 12345);
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
publishProgress("@success");
} catch (Exception e) {
Toast.makeText(MainActivity.this, "无法建立连接", 1000).show();
e.printStackTrace();
}
try {
String line;
while ((line = reader.readLine())!=null) {
publishProgress(line);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
} @Override
protected void onProgressUpdate(String... values) {
if (values[0].equals("@success")) {
Toast.makeText(MainActivity.this, "建立连接成功", 1000).show();
}
text.append("对方说:"+values[0]+"\n");
super.onProgressUpdate(values);
} };
read.execute();
} /**
* 发送
*/
public void send(){
try {
text.append("我说:"+edit.getText().toString()+"\n");
writer.write(edit.getText().toString()+"\n");
writer.flush();
edit.setText("");
} catch (Exception e) {
e.printStackTrace();
}
} @Override
public void onClick(View v) {
switch (v.getId()) {
//连接
case R.id.connect:
connect();
break;
//发送
case R.id.send:
send();
break;
}
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
} @Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

客户端任意开。。。

还有最重要的,别忘了在主配置文件里加入网络权限啊。。。

上一篇:【jquery ,ajax,php】加载更多实例


下一篇:ubuntu垃圾清理命令