Android6 Socket通信

服务器代码:


import java.net.*;
import java.io.*;
/**
* Description:
* <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
* <br/>Copyright (C), 2001-2014, Yeeku.H.Lee
* <br/>This program is protected by copyright laws.
* <br/>Program Name:
* <br/>Date:
* @author Yeeku.H.Lee kongyeeku@163.com
* @version 1.0
*/
public class SimpleServer
{
public static void main(String[] args)
throws IOException
{
// 创建一个ServerSocket,用于监听客户端Socket的连接请求
ServerSocket ss = new ServerSocket(30000); //①
// 采用循环不断接受来自客户端的请求
while (true)
{
// 每当接受到客户端Socket的请求,服务器端也对应产生一个Socket
Socket s = ss.accept();
OutputStream os = s.getOutputStream();
os.write("您好,您收到了服务器的新年祝福!\n"
.getBytes("utf-8"));
// 关闭输出流,关闭Socket
os.close();
s.close();
}
}
}

 

 

android代码:

package org.crazyit.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;

/**
* Description:
* <br/>site: <a href="http://www.crazyit.org">crazyit.org</a>
* <br/>Copyright (C), 2001-2014, Yeeku.H.Lee
* <br/>This program is protected by copyright laws.
* <br/>Program Name:
* <br/>Date:
* @author Yeeku.H.Lee kongyeeku@163.com
* @version 1.0
*/
public class SimpleClient extends Activity
{
EditText show;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
show = (EditText) findViewById(R.id.show);
new Thread()
{
@Override
public void run()
{
try
{
// 建立连接到远程服务器的Socket
Socket socket = new Socket("219.217.246.92" , 30000); //①
// 将Socket对应的输入流包装成BufferedReader
BufferedReader br = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
// 进行普通IO操作
String line = br.readLine();
show.setText("来自服务器的数据:" + line);
// 关闭输入流、socket
br.close();
socket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}.start();
}
}

 

 

layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText
android:id="@+id/show"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:editable="false"
android:cursorVisible="false"
/>
</LinearLayout>

 

 

androidxml:添加网络权限

<application android:icon="@drawable/ic_launcher" android:label="@string/app_name">
<activity android:name=".SimpleClient"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

</application>
<!-- 授权访问互联网-->
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>

 

主要客户机ip设置:

校园网可能不行,百度的ip不行,ipconfig查询。

posted @ 2015-05-15 17:14  hitz&x  阅读(202)  评论(0编辑  收藏  举报