安卓使用socket建立通信
来源:互联网 发布:星海乐器知乎 编辑:程序博客网 时间:2024/06/05 21:16
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText edtmsgcontent;
private Button btnSend;
private String IP = "192.168.1.118";
private int port = 8080;
private TextView current_ip;
private EditText et_ip1,et_ip2,et_ip3,et_ip4,et_port;
private Button btn_set_ip;
private TextView temp_message;
private Socket socket = null;
Thread thread=null;
private Timer timer;
private byte[] mbyte = new byte[READ_LENGTH];
private static final int READ_LENGTH = 10;
private DataInputStream dataInputStream = null;
private DataOutputStream dataOutputStream = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
current_ip = (TextView) findViewById(R.id.textView1);
et_ip1 =(EditText) findViewById(R.id.et_ip1);
et_ip2 =(EditText) findViewById(R.id.et_ip2);
et_ip3 =(EditText) findViewById(R.id.et_ip3);
et_ip4 =(EditText) findViewById(R.id.et_ip4);
et_port =(EditText) findViewById(R.id.editText5);
edtmsgcontent = (EditText) findViewById(R.id.editText6);
temp_message = (TextView) findViewById(R.id.textView6);
btn_set_ip = (Button) findViewById(R.id.button1);
btnSend = (Button) findViewById(R.id.button2);
current_ip.setText(IP + ":" + port);
btn_set_ip.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
setIP();
}
});
btnSend.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
String msg =edtmsgcontent.getText().toString();
if (!TextUtils.isEmpty(msg)){
try {
dataOutputStream.write(msg.getBytes());
dataOutputStream.flush();
}
catch (UnknownHostException e) {}
catch (IOException e) {}
}
}
});
startConnected();
}
private void startConnected(){
if(timer != null) {timer.cancel();}
if(socket !=null) {socket = null;}
if(thread !=null) {thread.interrupt();thread = null;}
new Thread(){
public void run() {
try {
socket =new Socket(IP,port);
socket.setSoTimeout(1000);
dataInputStream = new DataInputStream(
socket.getInputStream());
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
}
catch (SocketTimeoutException e) {}
catch (Exception e ) {}
startThread();
timer = new Timer();
timer.schedule(new TimerTask(){
@Override
public void run(){
Message message = new Message();
message.obj =mbyte;
message.what = 1;
handler.sendMessage(message);
}
},0,500);
}
}.start();
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if(msg.what == 1&& msg.obj !=null){
String s = new String(mbyte);
temp_message.setText(s);
}
}
};
private void startThread(){
thread = new Thread(new Runnable() {
public void run()
{
while (socket !=null && !socket.isClosed())
{
try
{
if (dataInputStream != null)
{
dataInputStream.read(mbyte);
}
}
catch (SocketTimeoutException e){}
catch (IOException e){}
}
}
});
thread.start();
}
protected void setIP() {
// TODO Auto-generated method stub
String ip1 = et_ip1.getText().toString();
String ip2 = et_ip2.getText().toString();
String ip3 = et_ip3.getText().toString();
String ip4 = et_ip4.getText().toString();
String port = et_port.getText().toString();
if (isIP(ip1) && isIP(ip2) && isIP(ip3) && isIP(ip4) &&isPort(port))
{
IP= ip1 + "." +ip2 + "." + ip3 + "." + ip4;
current_ip.setText(IP + ":" + port);
startConnected();
Toast.makeText(this, "配置成功", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(this, "IP或Port输入有误", Toast.LENGTH_LONG).show();
}
}
private boolean isPort(String s) {
int i = -1;
try {
i= Integer.parseInt(s);
} catch (NumberFormatException e) {
e.printStackTrace();
return false;
}
if (i > 0) {
port = i;
return true;
}
else {
return false;
}
}
private boolean isIP(String s)
{
int i = -1;
try
{
i= Integer.parseInt(s);
}catch (NumberFormatException e) {
e.printStackTrace();
return false;
}
if((i>=0)&&(i<255))
{
return true;
}
return false;
}
@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;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
下面为activity_main,xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.client.MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="当前连接IP:" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="当前IP" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="IP:" />
<EditText
android:id="@+id/et_ip1"
android:layout_width="44dp"
android:layout_height="wrap_content"
android:layout_weight="0.44"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/et_ip2"
android:layout_width="63dp"
android:layout_height="wrap_content"
android:ems="10" />
<EditText
android:id="@+id/et_ip3"
android:layout_width="43dp"
android:layout_height="wrap_content"
android:layout_weight="0.37"
android:ems="10" />
<EditText
android:id="@+id/et_ip4"
android:layout_width="49dp"
android:layout_height="wrap_content"
android:layout_weight="0.44"
android:ems="10" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PORT:" />
<EditText
android:id="@+id/editText5"
android:layout_width="74dp"
android:layout_height="wrap_content"
android:ems="10"
android:text="8080" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="配置并重新连接" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Socket Client!" />
</LinearLayout>
<EditText
android:id="@+id/editText6"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送" />
</LinearLayout>
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="显示接收信息" />
</LinearLayout>
- 安卓使用socket建立通信
- 安卓使用socket建立通信客户端不显示数据
- 安卓 使用socket进行通信
- 安卓Socket通信
- 安卓与PC使用USB一种Socket通信方案
- 安卓使用socket实现客户端服务器通信问题
- android socket通信建立
- swoole 建立socket通信
- 安卓与pc 的socket通信
- 安卓与pc 的socket通信
- 安卓手机Socket通信程序
- 安卓SOCKET通信数据传输乱码问题
- java36.Socket通信------ServerSocket的建立与使用示例
- java37.Socket通信------使用ServerSocket建立聊天服务器---1
- java38.Socket通信------使用ServerSocket建立聊天服务器---2
- socket编程(一)使用SOCK_STREAM建立可靠通信
- socket编程(一)使用SOCK_STREAM建立可靠通信
- 安卓开发笔记(三)------------使用手机关闭电脑(基于socket通信)
- 2.在 HTML 中使用 JavaScript
- 获取头条{3秒转换,轮播(HTTPURLconnection+handler)
- synergy一个鼠标控制多个电脑,synergy怎么用?synergy配置教程
- 用C语言实现: 输入日期然后计算两天后的日期
- python圣斗士修炼(十一):几种高级特性
- 安卓使用socket建立通信
- 关于对朴素贝叶斯的算法理解
- leetcode---valid-parentheses---栈
- 给定两个整形变量的值,将两个值的内容进行交换
- MUI索引列表自定义----添加热门、最近等多个模块
- Failed to initiate service connection to simulator
- java中的this
- maven 本地 jar 包各种加入方式(有坑)
- 我的 2017 校招总结