android socket 之間的資訊互動

來源:互聯網
上載者:User

標籤:android   style   blog   http   io   color   ar   os   使用   

建立java項目    

SocketServer.java

import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class SocketServer {

  private static ServerSocket serivce;

  

  public static void main(String[] args) throws IOException {

    socket1();
  }
  public static void socket1()throws IOException{
  serivce = new ServerSocket(30000);
  while (true) {
  //等待用戶端串連
    Socket socket = serivce.accept();
    new Thread(new AndroidRunable(socket)).start();
  }
  }

}

 

建立使用線程

 

AndroidRunable.java

 

package cn.socket.server;

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

public class AndroidRunable implements Runnable{
Socket socket = null;

public AndroidRunable(Socket socket) {
this.socket = socket;
}

@Override
public void run() {
// 向android用戶端輸出hello worild
String line = null;
InputStream input;
OutputStream output;
String str = "你好!hello word";
try {
//向用戶端發送資訊
output = socket.getOutputStream();
input = socket.getInputStream();
BufferedReader bff = new BufferedReader(
new InputStreamReader(input));
output.write(str.getBytes("UTF-8")); //這個編碼格式 可以使用gbk
output.flush();
//半關閉socket
socket.shutdownOutput();
//擷取用戶端的資訊
while ((line = bff.readLine()) != null) {
System.out.print("\n"+line);
}
//關閉輸入輸出資料流
output.close();
bff.close();
input.close();
socket.close();

} catch (IOException e) {
e.printStackTrace();
}
}

}

 

點擊運行 java 

建立android 項目

MainActivity.java 

 

package com.example.socketan;

import java.net.Socket;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity implements View.OnClickListener{
private EditText edt_ip, edt_socket, edt_connect;
private Button btn_socket;
private String ip="192.168.12.6";
private int tcp=30000;
Socket socket = null;
String buffer = "";
String geted1;
// 定義與伺服器通訊的子線程
// ClientThread clientThread;
public Handler myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 0x11) {
Bundle bundle = msg.getData();
edt_socket.append("server:"+bundle.getString("msg")+"\n");
}
}

};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt_ip = (EditText) findViewById(R.id.edt_ip);
edt_socket = (EditText) findViewById(R.id.edt_socket);
edt_connect = (EditText) findViewById(R.id.edt_connect);
btn_socket = (Button) findViewById(R.id.btn_socket);
btn_socket.setOnClickListener(this);
}

@Override
public void onClick(View view) {
if (view.getId() == R.id.btn_socket) {
geted1 = edt_connect.getText().toString();
edt_socket.append("client:"+geted1+"\n");
// 用戶端啟動ClientThread線程建立網路連接、讀取來自伺服器的資料
new MyThread(geted1,ip,tcp,myHandler).start();
}

}

}

 

 

建立android使用線程

 

MyThread.java

 

package com.example.socketan;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class MyThread extends Thread {
private String str,ip;
private int tcp;
Socket socket=null;
String buffer=null;
private Handler myHandler;
public MyThread(String str,String ip,int tcp,Handler myHandler){
this.str=str;
this.ip=ip;
this.tcp=tcp;
this.myHandler=myHandler;
}
@Override
public void run() {
super.run();
//定義訊息
Message msg = new Message();
msg.what = 0x11;
Bundle bundle = new Bundle();
bundle.clear();
try {
//串連伺服器 並設定連線逾時為5秒
socket = new Socket();
socket.connect(new InetSocketAddress(ip, tcp), 5000);
//擷取輸入輸出資料流
OutputStream ou = socket.getOutputStream();
BufferedReader bff = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
//讀取發來伺服器資訊
String line = null;
buffer="";
while ((line = bff.readLine()) != null) {
buffer = line + buffer;
}

//向伺服器發送資訊
ou.write(str.getBytes("gbk"));
ou.flush();
bundle.putString("msg", buffer.toString());
msg.setData(bundle);
//發送訊息 修改UI線程中的組件
myHandler.sendMessage(msg);
//關閉各種輸入輸出資料流
bff.close();
ou.close();
socket.close();
} catch (SocketTimeoutException aa) {
//連線逾時 在UI介面顯示訊息
bundle.putString("msg", "伺服器串連失敗!請檢查網路是否開啟");
msg.setData(bundle);
//發送訊息 修改UI線程中的組件
myHandler.sendMessage(msg);
} catch (IOException e) {
e.printStackTrace();
} catch(Exception e){
e.printStackTrace();
}
}
}

 

android socket 之間的資訊互動

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.