这是我的服务器代码
using System;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Collections;
using System.Threading;
public class SynchronousSocketListener
{
private const int portNum = 4444;
private static ArrayList ClientSockets;
private static bool ContinueReclaim = true;
private static Thread ThreadReclaim;
public static void StartListening()
{
ClientSockets = new ArrayList();
ThreadReclaim = new Thread(new ThreadStart(Reclaim));
ThreadReclaim.Start();
TcpListener listener = new TcpListener(portNum);
try
{
listener.Start();
int TestingCycle = 3;
int ClientNbr = 0;
// Start listening for connections.
Console.WriteLine("Waiting for a connection...");
while (TestingCycle > 0)
{
TcpClient handler = listener.AcceptTcpClient();
if (handler != null)
{
Console.WriteLine("Client#{0} accepted!", ++ClientNbr);
// An incoming connection needs to be processed.
lock (ClientSockets.SyncRoot)
{
int i = ClientSockets.Add(new ClientHandler(handler));
((ClientHandler)ClientSockets[i]).Start();
Console.WriteLine("Added sock {0}", i);
}
--TestingCycle;
}
else
break;
}
listener.Stop();
ContinueReclaim = false;
ThreadReclaim.Join();
foreach (Object Client in ClientSockets)
{
((ClientHandler)Client).Stop();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
private static void Reclaim()
{
while (ContinueReclaim)
{
lock (ClientSockets.SyncRoot)
{
for (int x = ClientSockets.Count - 1; x >= 0; x--)
{
Object Client = ClientSockets[x];
if (!((ClientHandler)Client).Alive)
{
ClientSockets.Remove(Client);
Console.WriteLine("A client left");
}
}
}
Thread.Sleep(200);
}
}
public static int Main(String[] args)
{
while (true)
{
StartListening();
}
return 0;
}
}
class ClientHandler
{
TcpClient ClientSocket;
bool ContinueProcess = false;
Thread ClientThread;
public ClientHandler(TcpClient ClientSocket)
{
this.ClientSocket = ClientSocket;
}
public void Start()
{
ContinueProcess = true;
ClientThread = new Thread(new ThreadStart(Process));
ClientThread.Start();
}
private void Process()
{
// Incoming data from the client.
string data = null;
// Data buffer for incoming data.
byte[] bytes;
if (ClientSocket != null)
{
NetworkStream networkStream = ClientSocket.GetStream();
ClientSocket.ReceiveTimeout = 100; // 1000 miliseconds
while (ContinueProcess)
{
bytes = new byte[ClientSocket.ReceiveBufferSize];
try
{
int BytesRead = networkStream.Read(bytes, 0, (int)ClientSocket.ReceiveBufferSize);
//BytesRead--;
if (BytesRead > 0)
{
Console.WriteLine("Bytes Read - Debugger " + BytesRead);
data = Encoding.ASCII.GetString(bytes, 0, BytesRead);
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
byte[] sendBytes = Encoding.ASCII.GetBytes("I rec ya abbas");
networkStream.Write(sendBytes, 0, sendBytes.Length);
if (data == "quit") break;
}
}
catch (IOException) { } // Timeout
catch (SocketException)
{
Console.WriteLine("Conection is broken!");
break;
}
Thread.Sleep(200);
} // while ( ContinueProcess )
networkStream.Close();
ClientSocket.Close();
}
} // Process()
public void Stop()
{
ContinueProcess = false;
if (ClientThread != null && ClientThread.IsAlive)
ClientThread.Join();
}
public bool Alive
{
get
{
return (ClientThread != null && ClientThread.IsAlive);
}
}
} // class ClientHandler
这是我的客户代码:
package com.example.socketclient;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.util.Log;
public class SocketCode extends Activity {
public TextView txt;
protected SocketCore Conn;
public Button b;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_socket_code);
b = (Button)findViewById(R.id.button1);
txt = (TextView)findViewById(R.id.textView1);
Conn = new SocketCore(this,txt);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Conn.execute();
}
});
}
}
套接字核心
package com.example.socketclient;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
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.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
class SocketCore extends AsyncTask<Context, Integer, String>
{
String text = "";
String finalText = "";
private Context ctx;
ProgressDialog dialog;
TextView Msg;
Socket socket;
public SocketCore(Context applicationContext,TextView Change)
{
// TODO Auto-generated constructor stub
ctx = applicationContext;
dialog = new ProgressDialog(applicationContext);
Msg = Change;
}
@Override
protected String doInBackground(Context... arg0) {
// TODO Auto-generated method stub
try {
InetAddress serverAddr = InetAddress.getByName("192.168.0.150");
Log.d("TCP", "C: Connecting....");
socket = new Socket(serverAddr,4444);
// Log.d("TCP", "C: I dunno ...");
String message = "Hello Server .. This is the android client talking to you .. First we are testing Server Crashing";
PrintWriter out = null;
BufferedReader in = null;
try {
Log.d("TCP", "C: Sending: '" + message + "'");
out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//serverReturnString = System.Text.Encoding.ASCII.GetString(response, 0, bytes);
out.println("quit");
//out.print("h");
while ((text = in.readLine()) != null) {
finalText += text;
if(text=="quit")
{
socket.close();
}
Log.d("TCP", "C: Done."+finalText);
}
// Msg.setText("LOLZ");
Log.d("TCP", "C: Sent.");
} catch(Exception e) {
Log.e("TCP", "S: Error", e);
} /*finally {
socket.close();
Log.d("TCP", "S: Closed");
} */
}catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e("TCP", "C: UnknownHostException", e);
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("TCP", "C: IOException", e);
e.printStackTrace();
}
//dialog.setMessage("Recieved: "+finalText);
return "COMPLETE";
}
protected void onPostExecute(String x)
{
super.onPostExecute("Finished");
dialog.dismiss();
Msg.setText(finalText);
}
protected void onPreExecute()
{dialog.setTitle("Initializing Connection");
dialog.setMessage("Connecting");
dialog.show();
}
}
服务器可以从安卓手机读取,安卓客户端也可以从服务器获取消息。问题是每当服务器检测到连接并开始 Receives text and Sends Reply 。之后代码不接受更多连接。
注意:我尝试使用 C# 客户端进行测试,它工作正常,所以我在客户端遇到问题