public class Server implements Runnable{ @Override public void run() { Socket socket = null; try { ServerSocket server = new ServerSocket(18888); //循环监听客户端链接请求 while(true){ System.out.println("start..."); //接收请求 socket = server.accept(); System.out.println("accept..."); //接收客户端消息 BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String message = in.readLine(); //发送消息,向客户端 PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true); out.println("Server:" + message); //关闭流 in.close(); out.close(); } } catch (IOException e) { e.printStackTrace(); }finally{ if (null != socket){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } //启动服务器 public static void main(String[] args){ Thread server = new Thread(new Server()); server.start(); } }
public class MainActivity extends Activity {
private EditText editText;
private Button button;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText = (EditText)findViewById(R.id.editText1);
button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Socket socket = null;
String message = editText.getText().toString()+ "\r\n" ;
try {
//创建客户端socket,注意:不能用localhost或127.0.0.1,Android模拟器把自己作为localhost
socket = new Socket("10.0.2.2",18888);
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter
(socket.getOutputStream())),true);
//发送数据
out.println(message);
//接收数据
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg = in.readLine();
if (null != msg){
editText.setText(msg);
System.out.println(msg);
}
else{
editText.setText("data error");
}
out.close();
in.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
try {
if (null != socket){
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
}
<?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"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <EditText android:layout_width="match_parent" android:id="@+id/editText1" android:layout_height="wrap_content" android:hint="input the message and click the send button" ></EditText> <Button android:text="send" android:id="@+id/button1" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button> </LinearLayout>
javac com/test/socket/Server.java java com.test.socket.Server运行客户端程序:
结果如图:
注意:服务器与客户端无法链接的可能原因有:<%@page language="java" import="java.util.*" pageEncoding="utf-8"%> <html> <head> <title> Http Test </title> </head> <body> <% String type = request.getParameter("parameter"); String result = new String(type.getBytes("iso-8859-1"),"utf-8"); out.println("<h1>" + result + "</h1>"); %> </body> </html>然后实现Android客户端,分别以post、get方式去访问myapp,代码如下:
<?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" > <TextView android:gravity="center" android:id="@+id/textView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:text="get" android:id="@+id/get" android:layout_width="match_parent" android:layout_height="wrap_content"></Button> <Button android:text="post" android:id="@+id/post" android:layout_width="match_parent" android:layout_height="wrap_content"></Button> </LinearLayout>资源文件:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">通过按钮选择不同方式访问网页</string> <string name="app_name">Http Get</string> </resources>主Activity:
public class MainActivity extends Activity { private TextView textView; private Button get,post; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textView = (TextView)findViewById(R.id.textView); get = (Button)findViewById(R.id.get); post = (Button)findViewById(R.id.post); //绑定按钮监听器 get.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //注意:此处ip不能用127.0.0.1或localhost,Android模拟器已将它自己作为了localhost String uri = "http://192.168.22.28:8080/myapp/http.jsp?parameter=以Get方式发送请求"; textView.setText(get(uri)); } }); //绑定按钮监听器 post.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String uri = "http://192.168.22.28:8080/myapp/http.jsp"; textView.setText(post(uri)); } }); } /** * 以get方式发送请求,访问web * @param uri web地址 * @return 响应数据 */ private static String get(String uri){ BufferedReader reader = null; StringBuffer sb = null; String result = ""; HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(uri); try { //发送请求,得到响应 HttpResponse response = client.execute(request); //请求成功 if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); sb = new StringBuffer(); String line = ""; String NL = System.getProperty("line.separator"); while((line = reader.readLine()) != null){ sb.append(line); } } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally{ try { if (null != reader){ reader.close(); reader = null; } } catch (IOException e) { e.printStackTrace(); } } if (null != sb){ result = sb.toString(); } return result; } /** * 以post方式发送请求,访问web * @param uri web地址 * @return 响应数据 */ private static String post(String uri){ BufferedReader reader = null; StringBuffer sb = null; String result = ""; HttpClient client = new DefaultHttpClient(); HttpPost request = new HttpPost(uri); //保存要传递的参数 List<NameValuePair> params = new ArrayList<NameValuePair>(); //添加参数 params.add(new BasicNameValuePair("parameter","以Post方式发送请求")); try { //设置字符集 HttpEntity entity = new UrlEncodedFormEntity(params,"utf-8"); //请求对象 request.setEntity(entity); //发送请求 HttpResponse response = client.execute(request); //请求成功 if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ System.out.println("post success"); reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); sb = new StringBuffer(); String line = ""; String NL = System.getProperty("line.separator"); while((line = reader.readLine()) != null){ sb.append(line); } } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally{ try { //关闭流 if (null != reader){ reader.close(); reader = null; } } catch (IOException e) { e.printStackTrace(); } } if (null != sb){ result = sb.toString(); } return result; } }
运行结果如下:
3.android.net编程: