求教,AS开发app问题
androidstudio吧
全部回复
仅看楼主
level 1
package com.example.administrator.myapp20173701;
import android.app.Activity;;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
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;
public class MainActivity extends Activity {
Socket socket = null;
String buffer = "";
TextView txt1;
Button send;
EditText ed1;
String geted1;
public Handler myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 0x11) {
Bundle bundle = msg.getData();
txt1.append("server:"+bundle.getString("message")+"\n");
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt1 = (TextView) findViewById(R.id.TextView01);
send = (Button) findViewById(R.id.Button01);
ed1 = (EditText) findViewById(R.id.EditText01);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
geted1 = ed1.getText().toString();
txt1.append("client:"+geted1+"\n");
//启动线程 接收服务器信息
new MyThread(geted1).start();
}
});
}
public class MyThread extends Thread {
public String txt1;
public MyThread(String str) {
txt1 = str;
}
@Override
public void run() {
//定义消息
Message msg = new Message();
msg.what = 0x11;
Bundle bundle = new Bundle();
try {
//连接服务器 并设置连接超时为4秒
socket = new Socket();
socket.connect(new InetSocketAddress("192.168.4.1",8080), 4000);
//获取输入流
OutputStream ou = socket.getOutputStream();
BufferedReader bff = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//读取服务器信息
String line = bff.readLine();
buffer="";
while(line != null){
buffer = line + buffer;
}
//向服务器发送信息
ou.write(txt1.getBytes("UTF-8"));
ou.flush();
bundle.putString("message",buffer.toString());
msg.setData(bundle);
//发送消息 修改UI线程中的组件
myHandler.sendMessage(msg);
//关闭各种输入输出流
bff.close();
ou.close();
socket.close();
} catch (SocketTimeoutException e) {
//连接超时 在UI界面显示消息
bundle.putString("message", "服务器连接失败!请检查网络是否打开");
msg.setData(bundle);
//发送消息 修改UI线程中的组件
myHandler.sendMessage(msg);
} catch (IOException e) {
bundle.putString("message", "Exception e");
msg.setData(bundle);
}
}
}
}
做一个手机app作为客户端 socket通信服务器 通过wifi 代码如上,真机测试了之后只能连接上服务器但是不能接受发送数据,为什么啊,求教
2017年03月07日 07点03分 1
1