我想构建一个示例Android应用程序,以通过TCP在另一台PC和我的Android应用程序之间建立基于套接字的连接。这是我的Client.java文件代码: -
package com.myApp.android.androidsocketclient;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.app.Instrumentation;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
public class Client extends Activity {
private Socket socket;
private static final int SERVERPORT = ****;
private static final String SERVER_IP = "***.**.**.**";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new Thread(new ClientThread()).start();
}
public void onClick(View view) {
Log.d("button click0", "happening");
RequestLogin("userid", "password", "123456");
/*try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}*/
}
class TMessageHeader {
public short MessageCode;
public int MessageLength;
public byte ChannelId;
public char[] ClientId = new char[16];
public int TimeStamp;
public int ErrorCode;
public int ErrorMessageLength;
public byte NumberOfDecimals;
public char Source;
public int ClientDispatcherID;
}
public TMessageHeader GetMessageHeader(String UserId, TLoginRequest pStructure) {
Log.d("MessageHeader", "called");
TMessageHeader msgHeader = new TMessageHeader();
msgHeader.ChannelId = 0;//Need to be set on the bases of user Scrip Selection for cash ==> 0 and for FnO not yet decided.
if (!UserId.isEmpty())
msgHeader.ClientId = UserId.toCharArray();
msgHeader.ErrorCode = 0;
msgHeader.ErrorMessageLength = 0;
msgHeader.MessageCode = 1;
msgHeader.MessageLength = 134;
msgHeader.NumberOfDecimals = 0;
msgHeader.Source = 'A';
msgHeader.TimeStamp = 0;
Log.d("Returned", String.valueOf(msgHeader));
return msgHeader;
}
class TLoginRequest {
TMessageHeader messageHeader;
char[] UserId = new char[20];
char[] Password = new char[16];
char[] IPAddress = new char[16];
char[] MacAddress = new char[20];
int VersionNo;
char[] PanOrDOB = new char[13];
}
public void RequestLogin(String pLoginId, String pPassword, String pPanDOB) {
Log.d("RequestLogin", "Called");
TLoginRequest request = new TLoginRequest();
request.IPAddress = "IPAddress".toCharArray();
request.MacAddress = "MacAddress".toCharArray();
request.PanOrDOB = pPanDOB.trim().toCharArray();
request.Password = pPassword.trim().toCharArray();
request.UserId = pLoginId.trim().toUpperCase().toCharArray();
request.VersionNo = Integer.parseInt("5");
request.UserId = "userid".toCharArray();
request.messageHeader = GetMessageHeader("userid", request);
request.messageHeader.ClientId = pLoginId.trim().toCharArray();
try {
if(socket != null) {
Log.d("Socket is not", "null");
Log.d("OutputStream", String.valueOf(socket.getOutputStream()));
OutputStreamWriter outwrite = new OutputStreamWriter(socket.getOutputStream());
BufferedWriter buffwrite = new BufferedWriter(outwrite);
PrintWriter out = new PrintWriter(buffwrite, true);
out.println(request);
}
Log.d("Socket is", "null");
} catch (IOException e) {
e.printStackTrace();
Log.d("IOException", "Occured");
}
}
class ClientThread implements Runnable {
@Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
Log.d("UnknownHostException", "true");
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
Log.d("IOException", "true");
}
}
}
}
当我运行此代码时,在日志中我得到Socket等于null。我该如何解决这个问题? 任何帮助都会受到极大关注。
日志文件: -
03-17 11:57:46.227: D/AndroidRuntime(293): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
03-17 11:57:46.227: D/AndroidRuntime(293): CheckJNI is ON
03-17 11:57:46.577: D/AndroidRuntime(293): Calling main entry com.android.commands.pm.Pm
03-17 11:57:46.597: I/ActivityManager(61): Start proc com.android.defcontainer for service com.android.defcontainer/.DefaultContainerService: pid=301 uid=10003 gids={1015, 2001}
03-17 11:57:46.798: D/dalvikvm(301): GC_EXPLICIT freed 292K, 54% free 2568K/5511K, external 1625K/2137K, paused 41ms
03-17 11:57:46.957: W/ActivityManager(61): No content provider found for:
03-17 11:57:47.007: W/ActivityManager(61): No content provider found for:
03-17 11:57:47.018: D/PackageParser(61): Scanning package: /data/app/vmdl-912569523.tmp
03-17 11:57:47.157: I/PackageManager(61): Removing non-system package:com.javacodegeeks.android.androidsocketclient
03-17 11:57:47.157: I/ActivityManager(61): Force stopping package com.javacodegeeks.android.androidsocketclient uid=10041
03-17 11:57:47.168: I/dalvikvm(61): Jit: resizing JitTable from 512 to 1024
03-17 11:57:47.248: D/PackageManager(61): Scanning package com.javacodegeeks.android.androidsocketclient
03-17 11:57:47.248: I/PackageManager(61): Package com.javacodegeeks.android.androidsocketclient codePath changed from /data/app/com.javacodegeeks.android.androidsocketclient-2.apk to /data/app/com.javacodegeeks.android.androidsocketclient-1.apk; Retaining data and using new
03-17 11:57:47.248: I/PackageManager(61): Unpacking native libraries for /data/app/com.javacodegeeks.android.androidsocketclient-1.apk
03-17 11:57:47.258: D/installd(35): DexInv: --- BEGIN '/data/app/com.javacodegeeks.android.androidsocketclient-1.apk' ---
03-17 11:57:47.908: D/dalvikvm(312): DexOpt: load 78ms, verify+opt 352ms
03-17 11:57:47.937: D/installd(35): DexInv: --- END '/data/app/com.javacodegeeks.android.androidsocketclient-1.apk' (success) ---
03-17 11:57:47.937: W/PackageManager(61): Code path for pkg : com.javacodegeeks.android.androidsocketclient changing from /data/app/com.javacodegeeks.android.androidsocketclient-2.apk to /data/app/com.javacodegeeks.android.androidsocketclient-1.apk
03-17 11:57:47.948: W/PackageManager(61): Resource path for pkg : com.javacodegeeks.android.androidsocketclient changing from /data/app/com.javacodegeeks.android.androidsocketclient-2.apk to /data/app/com.javacodegeeks.android.androidsocketclient-1.apk
03-17 11:57:47.948: D/PackageManager(61): Activities: com.javacodegeeks.android.androidsocketclient.Client
03-17 11:57:47.958: I/ActivityManager(61): Force stopping package com.javacodegeeks.android.androidsocketclient uid=10041
03-17 11:57:48.078: I/installd(35): move /data/dalvik-cache/data@app@com.javacodegeeks.android.androidsocketclient-1.apk@classes.dex -> /data/dalvik-cache/data@app@com.javacodegeeks.android.androidsocketclient-1.apk@classes.dex
03-17 11:57:48.078: D/PackageManager(61): New package installed in /data/app/com.javacodegeeks.android.androidsocketclient-1.apk
03-17 11:57:48.186: I/ActivityManager(61): Force stopping package com.javacodegeeks.android.androidsocketclient uid=10041
03-17 11:57:48.238: D/dalvikvm(130): GC_EXPLICIT freed 15K, 51% free 2906K/5895K, external 4767K/5643K, paused 49ms
03-17 11:57:48.318: I/ActivityManager(61): Start proc com.svox.pico for broadcast com.svox.pico/.VoiceDataInstallerReceiver: pid=313 uid=10009 gids={}
03-17 11:57:48.338: W/RecognitionManagerService(61): no available voice recognition services found
03-17 11:57:48.528: I/ActivityThread(313): Pub com.svox.pico.providers.SettingsProvider: com.svox.pico.providers.SettingsProvider
03-17 11:57:48.588: D/dalvikvm(170): GC_EXPLICIT freed 294K, 52% free 2771K/5703K, external 1625K/2137K, paused 342ms
03-17 11:57:48.658: D/dalvikvm(61): GC_EXPLICIT freed 1092K, 47% free 4277K/8007K, external 4373K/5573K, paused 75ms
03-17 11:57:48.738: I/installd(35): unlink /data/dalvik-cache/data@app@com.javacodegeeks.android.androidsocketclient-2.apk@classes.dex
03-17 11:57:48.748: D/AndroidRuntime(293): Shutting down VM
03-17 11:57:48.758: D/dalvikvm(293): GC_CONCURRENT freed 102K, 72% free 295K/1024K, external 0K/0K, paused 0ms+1ms
03-17 11:57:48.758: D/jdwp(293): Got wake-up signal, bailing out of select
03-17 11:57:48.758: D/dalvikvm(293): Debugger has detached; object registry had 1 entries
03-17 11:57:49.088: D/AndroidRuntime(326): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
03-17 11:57:49.088: D/AndroidRuntime(326): CheckJNI is ON
03-17 11:57:49.438: D/AndroidRuntime(326): Calling main entry com.android.commands.am.Am
03-17 11:57:49.448: I/ActivityManager(61): Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.javacodegeeks.android.androidsocketclient/.Client } from pid 326
03-17 11:57:49.468: I/ActivityManager(61): Start proc com.javacodegeeks.android.androidsocketclient for activity com.javacodegeeks.android.androidsocketclient/.Client: pid=334 uid=10041 gids={3003}
03-17 11:57:49.488: D/AndroidRuntime(326): Shutting down VM
03-17 11:57:49.498: D/dalvikvm(326): GC_CONCURRENT freed 103K, 69% free 319K/1024K, external 0K/0K, paused 1ms+1ms
03-17 11:57:49.498: D/dalvikvm(326): Debugger has detached; object registry had 1 entries
03-17 11:57:50.178: I/ARMAssembler(61): generated scanline__00000177:03515104_00001002_00000000 [ 87 ipp] (110 ins) at [0x44c766f0:0x44c768a8] in 366685 ns
03-17 11:57:50.468: I/ActivityManager(61): Displayed com.javacodegeeks.android.androidsocketclient/.Client: +1s9ms
03-17 11:57:55.568: D/dalvikvm(130): GC_EXPLICIT freed 128K, 51% free 2890K/5895K, external 4816K/5643K, paused 55ms
03-17 11:57:55.808: D/button click0(334): happening
03-17 11:57:55.808: D/RequestLogin(334): Called
03-17 11:57:55.808: D/MessageHeader(334): called
03-17 11:57:55.808: D/Returned(334): com.javacodegeeks.android.androidsocketclient.Client$TMessageHeader@405345f8
03-17 11:57:55.808: D/Socket is not(334): null
03-17 11:57:55.818: D/OutputStream(334): org.apache.harmony.luni.net.SocketOutputStream@40534ac8
03-17 11:57:55.818: D/Socket is(334): null
03-17 12:01:49.917: D/SntpClient(61): request time failed: java.net.SocketException: Address family not supported by protocol
答案 0 :(得分:1)
你得到Socket is(334): null
,因为你无条件地打印它。你错过了else.