分享到:
点击次数:333  更新时间:2016-10-11 16:24:04  【打印此页】  【关闭
棋牌游戏定制
当前位置:主页 > 新闻动态 > 技术交流 > Android使用Socket编程连接服务端

Android使用Socket编程连接服务端

责任编辑:admin 发布时间:2016-11-17 14:47 浏览次数:

首先,在一个Java工程中这样写
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class SimpleServer
{
 public static void main(String[] args) throws IOException
 {
  ServerSocket serverSocket = new ServerSocket(30000);
  while (true)
  {
   Socket socket = serverSocket.accept();
   InetAddress  inetAddress = socket.getInetAddress();
   System.out.println("IP地址的完全限定域名是:"+inetAddress.getCanonicalHostName()+"\n IP地址字符串为:"+
   inetAddress.getHostAddress()+"\n 主机名为:"+inetAddress.getHostName());
   OutputStream outputStream = socket.getOutputStream();
   outputStream.write("这是来自服务器的一句话\n".getBytes("utf-8"));
   
   outputStream.close();
   socket.close();
  }
  
 }
}
然后,在一个android 工程中这样写(布局上只有一个TextView,就不写了)
package com.example.socketandroid;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
 TextView show;
 String ip = "10.0.2.2";
 String line;
 Handler handler = new Handler() {
  public void handleMessage(Message msg) {
   if (msg.arg1 == 1) {
    String textFrom = msg.obj.toString();
    show.setText(textFrom);
   }
  };
 };
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  show = (TextView) findViewById(R.id.show);
  new Thread() {
   public void run() {
    try {
     Socket socket = new Socket(ip, 30000);
     BufferedReader bufferedReader = new BufferedReader(
       new InputStreamReader(socket.getInputStream()));
     line = bufferedReader.readLine();
     Message message = handler.obtainMessage();
     message.obj = line;
     message.arg1 = 1;
     handler.sendMessage(message);
    } catch (IOException e) {
     e.printStackTrace();
    }
   };
  }.start();
 }
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }
}
当然 不要忘了添加网络权限
接下来,先运行java工程,再运行android工程,可以看到textView变成了"这是来自服务器的一句话"