您的位置:首页 > 移动开发 > Android开发

Android与PC间进行Socket通信

2016-02-05 23:36 459 查看
自己写了一个小程序,是android手机与PC端通过Socket进行通信:

服务端

服务端是一段java代码,跑在PC上

public class SimpleServer {

JTextArea textArea;

Socket clientSocket;

public static void main(String[] args) {
new SimpleServer().go();
}

public void go() {
// 创建GUI
JFrame frame = new JFrame("客户端");
JPanel mainPanel = new JPanel();
textArea = new JTextArea(15, 28);
textArea.setLineWrap(true);
textArea.setEditable(false);
JScrollPane qScroller = new JScrollPane(textArea);
qScroller
.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
mainPanel.add(qScroller);
frame.getContentPane().add(mainPanel);
frame.setSize(400, 350);
frame.setVisible(true);

// 创建Socket并监听端口
new Thread(new Runnable() {

@Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(2000);
textArea.append("监听端口2000,等待连接中...\n");
while (true) {
clientSocket = serverSocket.accept();
textArea.append("连接成功!\n");

// 启动新线程,将收到的信息显示在屏幕上
new Thread(new ClientHandler()).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}

public class ClientHandler implements Runnable {

@Override
public void run() {
try {
InputStreamReader isReader = new InputStreamReader(
clientSocket.getInputStream());
BufferedReader reader = new BufferedReader(isReader);

String message;
while ((message = reader.readLine()) != null) {
textArea.append(message + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}

}

}

}


客户端

客户端是一段百度地图定位的代码,将当前位置发送给服务器,真正网络操作的代码其实很少

public class MainActivity extends Activity {

public TextView textView;

public LocationClient mLocationClient;

public Socket socket;
public PrintWriter writer;

public String time;
public double latitude;
public double longitude;
public String description;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.text_view);

mLocationClient = new LocationClient(getApplicationContext());
initLocation();
mLocationClient.registerLocationListener(new MyLocationListener());
mLocationClient.start();

// 初始化网络连接,为发送位置信息做准备
new Thread(new Runnable() {

@Override
public void run() {
try {
socket = new Socket("192.168.1.118", 2000);
Log.d("MainActivity", "网络初始化成功");
writer = new PrintWriter(socket.getOutputStream());
} catch (UnknownHostException e) {
e.printStackTrace();
Log.d("MainActivity", "未知主机地址");
} catch (IOException e) {
e.printStackTrace();
Log.d("MainActivity", "输入输出异常");
}
}

}).start();

}

private void initLocation() {
LocationClientOption option = new LocationClientOption();
option.setLocationMode(LocationMode.Hight_Accuracy);// 可选,默认高精度,设置定位模式,高精度,低功耗,仅设备
option.setCoorType("bd09ll");// 可选,默认gcj02,设置返回的定位结果坐标系
int span = 1000;
option.setScanSpan(span);// 可选,默认0,即仅定位一次,设置发起定位请求的间隔需要大于等于1000ms才是有效的
option.setIsNeedAddress(true);// 可选,设置是否需要地址信息,默认不需要
option.setOpenGps(true);// 可选,默认false,设置是否使用gps
option.setLocationNotify(true);// 可选,默认false,设置是否当gps有效时按照1S1次频率输出GPS结果
option.setIsNeedLocationDescribe(true);// 可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于“在北京天安门附近”
option.setIsNeedLocationPoiList(true);// 可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到
option.setIgnoreKillProcess(false);// 可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死
option.SetIgnoreCacheException(false);// 可选,默认false,设置是否收集CRASH信息,默认收集
option.setEnableSimulateGps(false);// 可选,默认false,设置是否需要过滤gps仿真结果,默认需要
mLocationClient.setLocOption(option);
}

public class MyLocationListener implements BDLocationListener {

@Override
public void onReceiveLocation(BDLocation location) {
// Receive Location
StringBuffer sb = new StringBuffer(256);
sb.append("time : ");
sb.append(location.getTime());
time = location.getTime();
sb.append("\nerror code : ");
sb.append(location.getLocType());
sb.append("\nlatitude : ");
sb.append(location.getLatitude());
latitude = location.getLatitude();
sb.append("\nlontitude : ");
sb.append(location.getLongitude());
longitude = location.getLongitude();
sb.append("\nradius : ");
sb.append(location.getRadius());
if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
sb.append("\nspeed : ");
sb.append(location.getSpeed());// 单位:公里每小时
sb.append("\nsatellite : ");
sb.append(location.getSatelliteNumber());
sb.append("\nheight : ");
sb.append(location.getAltitude());// 单位:米
sb.append("\ndirection : ");
sb.append(location.getDirection());// 单位度
sb.append("\naddr : ");
sb.append(location.getAddrStr());
sb.append("\ndescribe : ");
sb.append("gps定位成功");

} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
sb.append("\naddr : ");
sb.append(location.getAddrStr());
// 运营商信息
sb.append("\noperationers : ");
sb.append(location.getOperators());
sb.append("\ndescribe : ");
sb.append("网络定位成功");
} else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
sb.append("\ndescribe : ");
sb.append("离线定位成功,离线定位结果也是有效的");
} else if (location.getLocType() == BDLocation.TypeServerError) {
sb.append("\ndescribe : ");
sb.append("服务端网络定位失败,可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com,会有人追查原因");
} else if (location.getLocType() == BDLocation.TypeNetWorkException) {
sb.append("\ndescribe : ");
sb.append("网络不同导致定位失败,请检查网络是否通畅");
} else if (location.getLocType() == BDLocation.TypeCriteriaException) {
sb.append("\ndescribe : ");
sb.append("无法获取有效定位依据导致定位失败,一般是由于手机的原因,处于飞行模式下一般会造成这种结果,可以试着重启手机");
}
sb.append("\nlocationdescribe : ");
sb.append(location.getLocationDescribe());// 位置语义化信息
description = location.getLocationDescribe();
List<Poi> list = location.getPoiList();// POI数据
if (list != null) {
sb.append("\npoilist size = : ");
sb.append(list.size());
for (Poi p : list) {
sb.append("\npoi= : ");
sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
}
}
Log.i("BaiduLocationApiDem", sb.toString());
textView.setText(sb.toString());

// 发送地址信息
new Thread(new Runnable() {

@Override
public void run() {
writer.println(time + ": " + description);
writer.flush();
}

});

}
}

}


这里要注意android4.0以后都不允许在主线程中进行任何的网络操作,所以上面所有涉及到网络的操作都在新的线程里完成。

写这一段代码的初衷是想写一个能够远程发送定位信息的小应用,但是发现这种方法只能在局域网中进行通信(客户端中选择服务器的IP地址是192.168.1.118)。看来还要想想其它方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android socket java