求给一个安卓小程序的代码 就是单击按钮然后就与指定端口建立连接
我之前写过一个socket的demo,你参考一下来做吧,我这个写得很乱。
------------------------------------------------------------------------------
java代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class SocketTestActivity extends Activity {
public static final String TAG = SocketTestActivity.class.getSimpleName();
/* 服务器地址 */
private String host_ip = null;
/* 服务器端口 */
private int host_port = 0;
private Button btnConnect;
private Button btnSend;
private EditText editSend;
private EditText hostIP;
private EditText hostPort;
private Socket socket;
private PrintStream output;
private String buffer = "";
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_socket_test);
context = this;
initView();
btnConnect.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
host_ip = hostIP.getText().toString();
host_port = Integer.parseInt(hostPort.getText().toString());
new Thread(new ConnectThread()).start();
}
});
btnSend.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new SendThread(editSend.getText().toString())).start();
}
});
}
private void toastText(String message) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
public void handleException(Exception e, String prefix) {
e.printStackTrace();
toastText(prefix + e.toString());
}
public void initView() {
btnConnect = (Button) findViewById(R.id.btnConnect);
btnSend = (Button) findViewById(R.id.btnSend);
editSend = (EditText) findViewById(R.id.sendMsg);
hostIP = (EditText) findViewById(R.id.hostIP);
hostPort = (EditText) findViewById(R.id.hostPort);
}
private void closeSocket() {
try {
output.close();
socket.close();
} catch (IOException e) {
handleException(e, "close exception: ");
}
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (0x123 == msg.what) {
toastText("连接成功!");
}
}
};
/* 连接socket线程 */
public class ConnectThread implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
Message msg = Message.obtain();
try {
if (null == socket || socket.isClosed()) {
socket = new Socket();
socket.connect(new InetSocketAddress(host_ip,host_port),5000);
output = new PrintStream(socket.getOutputStream(), true,
"utf-8");
}
msg.what = 0x123;
handler.sendMessage(msg);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*发送信息线程*/
public class SendThread implements Runnable {
String msg;
public SendThread(String msg) {
super();
this.msg = msg;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
output.print(msg);
} catch (Exception e) {
e.printStackTrace();
}
closeSocket();
}
}
public class SocketThread implements Runnable {
public String txt1;
public SocketThread(String txt1) {
super();
this.txt1 = txt1;
}
@Override
public void run() {
// TODO Auto-generated method stub
Message msg = Message.obtain();
try {
/* 连接服务器 并设置连接超时为5秒 */
if (socket.isClosed() || null == socket) {
socket = new Socket();
socket.connect(new InetSocketAddress(host_ip,host_port),5000);
}
// 获取输入输出流
PrintStream ou = new PrintStream(socket.getOutputStream(),
true, "utf-8");
BufferedReader bff = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
// 读取发来服务器信息
String line = null;
buffer = "";
while ((line = bff.readLine()) != null) {
buffer = line + buffer;
}
// 向服务器发送信息
ou.print(txt1);
ou.flush();
// 发送消息 修改UI线程中的组件
// 关闭各种输入输出流
bff.close();
ou.close();
socket.close();
msg.what = 0x123;
handler.sendMessage(msg);
} catch (UnknownHostException e) {
handleException(e, "unknown host exception: " +
e.toString());
} catch (IOException e) {
handleException(e, "io exception: " + e.toString());`
}
}
}
private void sendMessage(String msg) {
output.print(msg);
}
}
-------------------------------------------------------------------------------------
布局文件:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/hostIP"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="服务器ip"
android:inputType="text" />
<EditText
android:id="@+id/hostPort"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numeric="integer"
android:inputType="number"
android:hint="端口"/>
<Button
android:id="@+id/btnConnect"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Connect" />
<EditText
android:id="@+id/sendMsg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="需要发送的内容"
android:inputType="text" />
<Button
android:id="@+id/btnSend"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Send" />
</LinearLayout>
还是连不上8500端口还是显示listening IP我把127.0.0.1换成了IPv4地址也还是不行 从模拟器到本地PC 换到了真机通过wifi与本地PC还是显示listening意思就是监听中 无连接请求
这安卓的socket是不是在安卓编程里面很高级的技术啊 我都搞了一天了 还是linstening不是established
安卓的socket通讯与java的socket通讯差不多,就是把socket连接的代码放到线程里执行。因为安卓4.0之后,网络请求不能直接放到主线程里,所以要开个线程来执行。你的服务器是自己写的?我是用“TCP-UDP服务管理”这个软件来测试的。测试能连接到服务器。
广告 您可能关注的内容 |