我已经为服务器消息发送应用程序创建了一个虚拟客户端。这里客户端是一个Android设备,服务器是简单的Java服务器,它在控制台上打印它收到的消息。我用套接字来实现这个。当我运行应用程序时,在客户端是Android设备时,从客户端发送消息和服务器在控制台上打印该消息之间会有2-3秒的延迟。但是,当客户端是另一台PC时,没有明显的延迟。如何消除这种延迟及其来源是什么?有人请帮忙!
我的服务器代码是:
import java.net.*;
import java.io.*;
class Server
{
void connectNread()
{
System.out.println("Server Started!! ... ");
try
{
ServerSocket ss = new ServerSocket(5000);
Socket s = ss.accept();
System.out.println(s.getInetAddress().getHostName() + " Connected!!!");
InputStreamReader stream = new InputStreamReader(s.getInputStream());
BufferedReader reader = new BufferedReader(stream);
String message = null;
message = reader.readLine();
long output = System.currentTimeMillis();
System.out.println(output+" : " + message);
stream.close();
s.close();
ss.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String s[])
{
new Server().connectNread();
}
}
Android客户端的代码是:
public class MainActivity extends ActionBarActivity {
Button connectButton;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectButton = (Button)findViewById(R.id.connect);
}
private class connectToNetwork extends AsyncTask<Integer,Integer,Integer>
{
protected Integer doInBackground(Integer... i)
{
try
{
Socket s = new Socket("192.168.1.22",5000);
PrintWriter writer = new PrintWriter(s.getOutputStream());
writer.println("Its Printed!!");
writer.flush();
writer.close();
s.close();
}
catch(Exception e)
{
System.out.println(e);
}
return 1;
}
protected void onProgressUpdate(Integer progress)
{
///setProgressPercent(progress[0]);
}
protected void onPostExecute(Integer result)
{
//showDialog("Downloaded " + result + " bytes");
}
}
public void connect(View v)
{
String TAG = null;
new connectToNetwork().execute(1,1,1);
}
@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;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
请建议我在哪里做错。所有设备都在同一个wifi网络上。