整个项目分为服务器端和客户端。服务器端用java编写,客户端为android。
服务器端:
- MyServerSocket.java : 主程序
package mypackage; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import javax.swing.JOptionPane; public class MyServerSocket { public static void main(String[] args) { // TODO Auto-generated method stub new ServerListener().start(); //创建一个线程用于监听socket } }
- ServerListener.java :监听器,用来捕获socket,并为之创建socket,并且添加到管理器ChatManager中
创建的ServerSocket 端口号一般需要大于10000,以免与PC端口冲突。package mypackage; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import javax.swing.JOptionPane; public class ServerListener extends Thread{ public void run(){ try { ServerSocket serverSocket=new ServerSocket(30002); while(true){ Socket socket=serverSocket.accept(); JOptionPane.showMessageDialog(null,"有客户端连接到端口30002"); ChatSocket chatsocket=new ChatSocket(socket); chatsocket.start(); ChatManager.getChatManager().add(chatsocket); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
- ChatSocket.java 负责给接收到的Socket一个线程,使其能够接收其他socket的数据,并写入自己的信息。
package mypackage; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.Socket; public class ChatSocket extends Thread { Socket socket; public ChatSocket(Socket socket){ this.socket=socket; } public void out(String out){ try { socket.getOutputStream().write(out.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void run(){ try { BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8")); String line=null; System.out.println(line); while((line=br.readLine())!=null){ System.out.println(line); ChatManager.getChatManager().publish(this, line+"\n");//发送给所有人,一点要加上换行符,否则android客户端接收不到 } br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
- ChatManager.java 通过创建Vector<ChatSocket>来管理ChatSocket。
package mypackage; import java.util.Vector; public class ChatManager { 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(ChatSocket cs,String out){ for(int i=0;i<vector.size();i++){ ChatSocket csChatSocket=vector.get(i); if(!cs.equals(csChatSocket)){ csChatSocket.out(out); } } } }
说明:以上代码在eclipse中运行。查看运行结果时,Win+R 打开cmd ,输入 telnet localhost 30002 即可连接到服务端。
客户端:
客户端需要创建socket套接字,发送自己的信息并接收其他信息。
MyActivity.java:
package com.example.hujiaxuan.mysocketclient;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
public class MyActivity extends Activity {
EditText ip;
EditText editText;
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
ip = (EditText) findViewById(R.id.id_et_ip);
editText = (EditText) findViewById(R.id.id_et_input);
text = (TextView) findViewById(R.id.id_tv_msg);
findViewById(R.id.id_btn_connect).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
connect();
}
});
findViewById(R.id.id_btn_send).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
send();
}
});
}
//-------------------------------------
Socket socket = null;
BufferedWriter writer = null;
BufferedReader reader = null;
public void connect(){
Toast.makeText(MyActivity.this,"成功",Toast.LENGTH_SHORT).show();
AsyncTask<Void,String,Void> read=new AsyncTask<Void, String, Void>() {
@Override
protected Void doInBackground(Void... voids) {
try{
socket=new Socket("10.12.77.17",30002);
writer=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
reader=new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
publishProgress("@success");
}catch (UnknownHostException e){
e.printStackTrace();
Toast.makeText(MyActivity.this,"无法建立连接",Toast.LENGTH_SHORT).show();
}catch (IOException e){
e.printStackTrace();
Toast.makeText(MyActivity.this,"无法建立连接",Toast.LENGTH_SHORT).show();
}
try{
String line;
while((line=reader.readLine())!=null){
System.out.println(line);
publishProgress(line);
}
}catch (IOException e){
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(String... values) {
if(values[0].equals("@success")){
Toast.makeText(MyActivity.this,"连接成功",Toast.LENGTH_SHORT).show();
}
text.append("别人说:"+values[0]+"\n");
super.onProgressUpdate(values);
}
};
read.execute();
}
public void send(){
try{
text.append("我说:"+editText.getText().toString()+"\n");
writer.write(editText.getText().toString()+"\n");
writer.flush();
editText.setText("");
}catch (IOException e){
e.printStackTrace();
}
}
}
activity_my.xml:
<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=".MyActivity">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<EditText
android:layout_width="300dp"
android:id="@+id/id_et_ip"
android:layout_height="wrap_content"
android:hint="请输入Ip地址"/>
<Button
android:layout_width="wrap_content"
android:id="@+id/id_btn_connect"
android:layout_height="wrap_content"
android:text="连接"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="hello!world"
android:id="@+id/id_tv_msg"/>
</ScrollView>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:orientation="vertical"
android:layout_height="wrap_content"
android:layout_marginTop="200dp"
>
<EditText
android:layout_width="fill_parent"
android:id="@+id/id_et_input"
android:layout_height="wrap_content"
android:hint="在这里输入内容"/>
<Button
android:layout_width="fill_parent"
android:id="@+id/id_btn_send"
android:layout_height="wrap_content"
android:text="发送"/>
</LinearLayout>
</LinearLayout>