Android 安卓插座果冻豆
我想问一些关于android socket的问题。我创建了一个示例应用程序,将数据发送到wifly模块。但当我从模块接收数据时,我得到套接字超时异常。不使用Android 安卓插座果冻豆,android,sockets,stream,android-4.2-jelly-bean,Android,Sockets,Stream,Android 4.2 Jelly Bean,我想问一些关于android socket的问题。我创建了一个示例应用程序,将数据发送到wifly模块。但当我从模块接收数据时,我得到套接字超时异常。不使用设置otimeout应用程序冻结到输入流。读取。这是我的密码: package com.socket.wiflysocket; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; impor
设置otimeout
应用程序冻结到输入流。读取。这是我的密码:
package com.socket.wiflysocket;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
protected static final String TAG = "WIflySocket";
EditText textOut;
TextView textIn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textOut = (EditText)findViewById(R.id.textout);
Button buttonSend = (Button)findViewById(R.id.send);
textIn = (TextView)findViewById(R.id.textin);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
@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;
}
Button.OnClickListener buttonSendOnClickListener
= new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo == null || networkInfo.isConnected() == false) {
try {
throw new Exception("Network is not connected");
} catch (Exception e) {
e.printStackTrace();
}
}
else {
new SocketThread(textOut.getText().toString()).execute();
textOut.setText("");
}
}};
}
和任务:
package com.socket.wiflysocket;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.util.Log;
public class SocketThread extends AsyncTask<String, Void, String>{
private static final String TAG = "SocketAsyncTask";
private static final int BUFFER_SIZE = 8;
private String textViewIn;
private String output;
private Socket socket = null;
private PrintWriter outputStream;
private InputStreamReader inputStream;
public SocketThread(String paramTextViewIn)
{
this.textViewIn = paramTextViewIn;
}
@Override
protected String doInBackground(String ...views) {
Log.d(TAG, "Execute");
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("1.2.3.4", 2000);
socket.setSoTimeout(2000);
outputStream = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
inputStream = new InputStreamReader(socket.getInputStream());
if(socket.isConnected()) {
this.sendDataWithString(textViewIn);
output = this.receiveDataFromServer();
}
this.closeSocket();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return output;
}
/*
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
return textViewOut;
}
*/
private void closeSocket() {
if (socket != null) {
if (socket.isConnected()) {
try {
inputStream.close();
outputStream.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void sendDataWithString(String message) {
if (message != null) {
outputStream.write(message);
outputStream.flush();
}
}
private String receiveDataFromServer() {
String message = "";
try {
int charsRead = 0;
char[] buffer = new char[BUFFER_SIZE];
while ((charsRead = inputStream.read(buffer)) != -1) {
message += new String(buffer).substring(0, charsRead);
}
closeSocket();
return message;
} catch (IOException e) {
//TODO work around
return message;
//return "Error receiving response: " + e.getMessage();
}
}
}
package com.socket.wiflysocket;
导入java.io.BufferedReader;
导入java.io.DataInputStream;
导入java.io.DataOutputStream;
导入java.io.IOException;
导入java.io.InputStreamReader;
导入java.io.OutputStreamWriter;
导入java.io.PrintWriter;
导入java.net.Socket;
导入java.net.UnknownHostException;
导入android.os.AsyncTask;
导入android.util.Log;
公共类SocketThread扩展异步任务{
私有静态最终字符串标记=“SocketAsyncTask”;
专用静态最终整数缓冲区大小=8;
私有字符串textViewIn;
私有字符串输出;
私有套接字=空;
私有PrintWriter输出流;
私有InputStreamReader inputStream;
公共SocketThread(字符串paramTextViewIn)
{
this.textViewIn=paramTextViewIn;
}
@凌驾
受保护的字符串背景(字符串…视图){
Log.d(标记“执行”);
DataOutputStream DataOutputStream=null;
DataInputStream DataInputStream=null;
试一试{
插座=新插座(“1.2.3.4”,2000年);
插座.设置插座输出(2000年);
outputStream=新的PrintWriter(新的OutputStreamWriter(socket.getOutputStream());
inputStream=新的InputStreamReader(socket.getInputStream());
if(socket.isConnected()){
this.sendDataWithString(textViewIn);
output=this.receiveDataFromServer();
}
这个.closeSocket();
}捕获(未知后异常e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
最后{
if(套接字!=null){
试一试{
socket.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
如果(dataOutputStream!=null){
试一试{
dataOutputStream.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
如果(dataInputStream!=null){
试一试{
dataInputStream.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
返回输出;
}
/*
//onPostExecute显示异步任务的结果。
@凌驾
受保护的void onPostExecute(字符串结果){
返回文本视图;
}
*/
私有void closeSocket(){
if(套接字!=null){
if(socket.isConnected()){
试一试{
inputStream.close();
outputStream.close();
socket.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
}
私有void sendDataWithString(字符串消息){
如果(消息!=null){
outputStream.write(消息);
outputStream.flush();
}
}
私有字符串receiveDataFromServer(){
字符串消息=”;
试一试{
int charsRead=0;
char[]buffer=新字符[buffer_SIZE];
而((charsRead=inputStream.read(缓冲区))!=-1){
message+=新字符串(缓冲区)。子字符串(0,charsRead);
}
closeSocket();
返回消息;
}捕获(IOE异常){
//待办事项
返回消息;
//返回“接收响应时出错:”+e.getMessage();
}
}
}
我添加的权限是:
android.permission.INTERNET
;
android.permission.ACCESS\u NETWORK\u STATE
你能告诉我,出了什么问题,以及如何解决这个问题吗。
谢谢你试试这个-
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
还是这个-
Reader r = new InputStreamReader(conn.getInputStream());
String line;
StringBuilder sb = new StringBuilder();
char[] chars = new char[4*1024];
int len;
while((len = r.read(chars))>=0) {
sb.append(chars, 0, len);
}
或者这一个——
byte[] resultBuff = new byte[0];
byte[] buff = new byte[1024];
int k = -1;
while((k = sock.getInputStream().read(buff, 0, buff.length)) > -1) {
byte[] tbuff = new byte[resultBuff.length + k];
System.arraycopy(resultBuff, 0, tbuff, 0, resultBuff.length); bytes
System.arraycopy(buff, 0, tbuff, resultBuff.length, k);
resultBuff = tbuff;
}
SocketFactory为您创建套接字
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import javax.net.SocketFactory;
...
private Socket socket = null;
public Reader reader = null;
public Writer writer = null;
protected void init(String host, int port) throws ClientException {
try {
socket = SocketFactory.getDefault().createSocket(host, port);
} catch (UnknownHostException e) {
throw new ClientException(e);
} catch (IOException e) {
throw new ClientException(e);
}
initDataManagers();
}
protected void initDataManagers() throws ClientException {
try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new ClientException(e);
} catch (IOException e) {
throw new ClientException(e);
}
}
inputStream.read()
阻塞,直到输入数据可用、检测到文件结尾或引发异常。调试应用程序时我注意到了这一点,但如何获取数据结尾?在调试模式下,我查看将数据发送到通过串行端口连接到wifly的wifly In终端(teraterm)。从wifly发送的数据是Hello
,但我在套接字引发异常时得到它。我是套接字编程新手,不知道如何正确实现。我在任何情况下都会尝试这段代码,线程冻结在读取方法中,并使用套接字超时验证退出。当删除设置otimeout
并尝试再次发送数据时,不会从wifly模块接收数据,读取后的日志也不会打印。这是果冻豆的问题吗?只解决了exeption工作,但我不能检查响应并在检查响应代码后发送数据。