利用wifi在同一个局域网下实现两部手机之间的通讯

需要用到的权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
service端
public class MainActivity extends Activity {
private Button start = null;
private EditText bufferText = null;
private Button send = null;
private ServerThread serverThread = null;
private String sendBuffer = null;
private String receiveBuffer = null;
private TcpSocketServer tss = null;
private TextView receiveView = null;
private Handler handler = new Handler(){//线程与UI交互更新界面
public void handleMessage(Message msg){
receiveView.setText(receiveBuffer);
Toast.makeText(MainActivity.this, receiveBuffer, Toast.LENGTH_SHORT).show();
}
};
private String intToIp(int i) {
return (i & 0xFF ) + "." +
((i >> 8 ) & 0xFF) + "." +
((i >> 16 ) & 0xFF) + "." +
( i >> 24 & 0xFF) ;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取wifi服务
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
//判断wifi是否开启
if (!wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(true);
}
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
String ip = intToIp(ipAddress);
TextView tv=(TextView) findViewById(R.id.ip);
tv.setText("本机IP:"+ip);
receiveView = (TextView)this.findViewById(R.id.receiveID);
start = (Button) this.findViewById(R.id.startID);
//监听服务器开启
start.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if(serverThread == null){
EditText portEditText = (EditText)MainActivity.this.findViewById(R.id.portID);
String port = portEditText.getText().toString().trim();
serverThread = new ServerThread(port);
serverThread .start();
Toast.makeText(MainActivity.this, port, Toast.LENGTH_SHORT).show();
}
}});
send = (Button)this.findViewById(R.id.sendID);
bufferText = (EditText)this.findViewById(R.id.bufferID);
//监听发送信息
send.setOnClickListener(new OnClickListener() {
public void onClick(View v){
sendBuffer = bufferText.getText().toString().trim();
if(sendBuffer != null)//为了避免线程把它弄为buffer = null;
Toast.makeText(MainActivity.this, sendBuffer, Toast.LENGTH_SHORT).show();
}
});
}
class ServerThread extends Thread{
private int port;
public ServerThread (String port){
this.port = Integer.parseInt(port);
}
public void run(){
//建立服务端
if(tss == null)
tss = new TcpSocketServer(this.port);
new Thread(new WriteThread()).start();//开启“写”线程
new Thread(new ReadThread()).start();//开启“读”线程
}
private class ReadThread implements Runnable{
public void run(){
while(true){
if((receiveBuffer = tss.getMessage()) != null){//收到不为null的信息就发送出去
handler.sendEmptyMessage(0);
}
}
}
}
private class WriteThread implements Runnable{
public void run(){
while(true){
try {
//发送数据
if(sendBuffer != null){
//tss.sendMessage(1821,buffer);
tss.sendMessage(sendBuffer);
sendBuffer = null;//清空,不让它连续发
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
public class TcpSocketServer {
private ServerSocket ss =null;
private Socket s = null;
private OutputStream out = null;
private InputStream in = null;
private String receiveBuffer = null;
public TcpSocketServer(int port){
//新建ServerSocket对象,端口为传进来的port;
try {
//ss= new ServerSocket(1821);
System.out.print("no");
ss = new ServerSocket(port);
System.out.print("yes");
s = ss.accept();
out = s.getOutputStream();
in = s.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMessage(String buffer)throws Exception{
//新建Socket通信对象,接受客户端发来的请求accept();
//Socket s = ss.accept();
//创建输入流对象InputStream
InputStream bais = new ByteArrayInputStream(buffer.getBytes());
byte[] buff = new byte[1024];
bais.read(buff);
out.write(buff);
out.flush();
}
public String getMessage(){
byte[] temp = new byte[1024];
try{
if(in.read(temp) > 0)
{
return receiveBuffer = new String(temp).trim();
}} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public String receiveMessage(){
return null;
}
}
client端
public class MainActivity extends Activity {
private EditText ipEdit = null;
private EditText portEdit = null;
private EditText buffEdit = null;
private Button startButton = null;
private Button sendButton = null;
private TextView receiveView = null;
private Socket s = null;
private byte[] receiveBuffer = new byte[1024];
private String sendBuffer = new String();
private String ip = null;
private int port ;
private int cmdCount = 0;
private Handler handler = new Handler(){//线程与UI交互更新界面
public void handleMessage(Message msg){
receiveView.setText(new String(receiveBuffer).trim());
Arrays.fill(receiveBuffer, (byte)0);//清空
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.init();
/*开启socket通信*/
startButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(s == null){//这里要设置验证!!!!!!!!!
/*设定ip和port*/
ip = ipEdit.getText().toString();
port = Integer.parseInt(portEdit.getText().toString());
/*开启socket线程*/
new Thread(new SocketClientControl(ip,port)).start();
}
Toast.makeText(MainActivity.this, "服务器连接成功", Toast.LENGTH_SHORT).show();
}
});
/*发送数据*/
sendButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
if(s != null)
sendBuffer = buffEdit.getText().toString();
Toast.makeText(MainActivity.this, "send -> "+sendBuffer, Toast.LENGTH_SHORT).show();
}
});
}
private void init(){
startButton = (Button) this.findViewById(R.id.startID);
sendButton = (Button) this.findViewById(R.id.sendID);
ipEdit = (EditText) this.findViewById(R.id.ipID);
portEdit = (EditText) this.findViewById(R.id.portID);
buffEdit = (EditText) this.findViewById(R.id.buffID);
receiveView = (TextView) this.findViewById(R.id.recieiveID);
}
private class SocketClientControl implements Runnable{
private InputStream in = null;
private OutputStream out = null;
public SocketClientControl(){
}
public SocketClientControl(String ip,int port){
try {
s = new Socket(ip,port);//获得链接
in = s.getInputStream();//获得输入流
out = s.getOutputStream();//获得输出流
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);//要是出问题,就线程退出
}
}
public void run(){
new Thread(new WriteThread()).start();//开启“写”线程
new Thread(new ReadThread()).start();//开启“读”线程
}
private class ReadThread implements Runnable{
public void run() {
while(true){
try {
if(in.read(receiveBuffer) > 0){//等待命令的输入
cmdCount ++; ;
handler.sendEmptyMessage(0);//发送信息,更新UI
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private class WriteThread implements Runnable{
public void run(){
while(true){
if(!sendBuffer.equals("")){
try {
out.write(sendBuffer.getBytes());//输出
out.flush();//输出刷新缓冲
} catch (IOException e) {
e.printStackTrace();
}
sendBuffer = "";
}
}
}
}
}
}
public class SocketClientSingle {
private static Socket s = null;
private SocketClientSingle()
{
}
public static Socket getSocket(String ip,int port){
try {
s = new Socket(ip,port);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
}