//--------------------------------创建 client 类-------------------------------------
package com.example.mianchuan;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
import android.content.Context;
import android.util.Log;
public class Client {
private PrintWriter pw=null;
private BufferedReader br=null;
private Socket s;
String jieguo;
/**
* @param args
*/
public String GetZhiFu(Context context,String ip,String dingdanhao) {
try {
Socket s=new Socket(ip,4545);
pw=new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
// DataInputStream input=new DataInputStream(s.getInputStream());
// String zhifuxinxi=dingdanhao;
pw.println(dingdanhao);
pw.flush();
jieguo=br.readLine();
Log.i("Log", "Client读到:"+jieguo);
}catch (Exception e) {
e.printStackTrace();
}
return jieguo;
}
}
//------------------------获取本机ip-------------------------------
package com.example.mianchuan;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;
public class GetIP {
public static String intToIp(int ipInt) {
StringBuilder sb = new StringBuilder();
sb.append(ipInt & 0xFF).append(".");
sb.append((ipInt >> 8) & 0xFF).append(".");
sb.append((ipInt >> 16) & 0xFF).append(".");
sb.append((ipInt >> 24) & 0xFF);
return sb.toString();
}
// 获取本地IP函数
public String getLocalIPAddress(Context context){
String ipv4 = null;
ConnectivityManager conMann = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
// NetworkInfo mobileNetworkInfo = conMann.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
NetworkInfo wifiNetworkInfo = conMann.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
try {
ArrayList
for (NetworkInterface ni : nilist) {
ArrayList
for (InetAddress address : ialist) {
if (!address.isLoopbackAddress()&&wifiNetworkInfo.isConnected()) {
ipv4 = address.getHostAddress();
WifiManager wifiManager = (WifiManager)context. getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
ipv4 = intToIp(ipAddress);
}
}
}
} catch (SocketException ex) {
Log.e("local ip", ex.toString());
}
return ipv4;
}
}
///==================================================
package com.example.mianchuan;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import com.youxi.zhipai.utils.GetIpText;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
//-----------------------------------创建服务端-----------------------------
public class SocketServer {
private static SharedPreferences sp;
private static Context mContect;
private static String lola = null;//经纬度
private static String addr = null;//详细地址
private static String province =null;//省
private static String city =null;//市
private static String district = null;//区
private static String street = null;//街道
private static String streetnumber = null;
private static String locationdescribe = null;
private static GetIpText getIpText=new GetIpText();
private static Map
private static ServerThread serverThread = null;
private static PrintStream writer;
private static class ServerThread implements Runnable {
private int port = 4545;
private boolean isExit = false;
private ServerSocket server;
public ServerThread() {
try {
server = new ServerSocket(port);
Log.i("Log", "启动服务成功" + "port:" + port);
} catch (IOException e) {
Log.i("Log","启动server失败,错误原因:" + e.getMessage());
}
}
@Override
public void run() {
try {
while (!isExit) {
// 进入等待环节
Log.i("Log","等待设备的连接... ... ");
final Socket socket = server.accept();
// 获取手机连接的地址及端口号
final String address = socket.getRemoteSocketAddress().toString();
Log.i("Log","连接成功,连接的设备为:" + address);
new Thread(new Runnable() {
@Override
public void run() {
try {
// 单线程索锁
synchronized (this){
// 放进到Map中保存
clientList.put(address,socket);
}
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String clientInputStr = input.readLine();//这里要注意和客户端输出流的写方法对应,否则会抛 EOFException
// 处理客户端数据
;
Log.i("Log", "客户端发过来的内容:" + clientInputStr);
getIpText.getServertext(clientInputStr);
socket.shutdownInput();
// 在这里群发消息
sendGps();
}catch (Exception e){
e.printStackTrace();
Log.i("Log","错误信息为:" + e.getMessage());
}finally {
synchronized (this){
Log.i("Log","关闭链接:" + address);
clientList.remove(address);
}
}
}
}).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void Stop(){
isExit = true;
if (server != null){
try {
server.close();
Log.i("Log","已关闭server");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static ServerThread startServer(Context contect){
mContect=contect;
Log.i("Log","开启服务");
if (serverThread != null){
showDown();
}
serverThread = new ServerThread();
new Thread(serverThread).start();
Log.i("Log","开启服务成功");
return serverThread;
}
// 关闭所有server socket 和 清空Map
public static void showDown(){
if (serverThread!=null&&clientList!=null){
for (Socket socket : clientList.values()) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (writer!=null){
writer.close();
}
serverThread.Stop();
clientList.clear();
}
}
// 群发的方法
public static boolean sendMsgAll(){
try {
for (Socket socket : clientList.values()) {
String returnServer="lola="+lola+"&addr="+addr+"&province="+province+"&city="+city+"&district="+district+"&street="+ street+"&streetnumber="+streetnumber+"&locationdescribe="+locationdescribe;
if (writer!=null){
writer.close();
}
writer = new PrintStream(socket.getOutputStream());//告诉客户端连接成功 并传状态过去
writer.println("HTTP/1.1 200 OK");// 返回应答消息,并结束应答
writer.println("Content-Length: "+ returnServer.getBytes().length );// 返回内容字节数
writer.println("Content-Type: text/plain;charset=utf-8");
writer.println();// 根据 HTTP 协议, 空行将结束头信息
writer.write(returnServer.getBytes());
writer.flush();
// 关闭输出流
socket.shutdownOutput();
}
return true;
}catch (Exception e){
e.printStackTrace();
}
return false;
}
private static void sendGps(){
sp = mContect.getSharedPreferences("Location", Context.MODE_PRIVATE);
province = sp.getString("province","");
city = sp.getString("city","");
district = sp.getString("district","");
street = sp.getString("street","");
streetnumber = sp.getString("streetnumber","");
locationdescribe = sp.getString("locationdescribe","");
lola = sp.getString("lola","");
addr = sp.getString("addr","");
sendMsgAll();
}
}
//-------------------------------使用----------------------------------
activity 中启动服务端 调用
private SocketServer server=new SocketServer();
server.startServer(this);
启动客户端 调用
Client client=new Client();
client.GetZhiFu(this,"服务器ip,既对方手机ip", "要发送的内容");