线上效果图:
服务端接收到的。
客户端接受到服务器返回的。
server端代码直接运行在本地就可以了。
手机客户端运行在手机上就行。
先安装客户端,再启动server。然后再输入文字,点击发送。
server端:
package server; import java.io.*;
import java.net.ServerSocket;
import java.net.Socket; public class AndroidServer implements Runnable{
public void run() {
try {
ServerSocket serverSocket=new ServerSocket(54321);
while(true)
{
System.out.println("等待接收用户连接:");
//接受客户端请求
Socket client=serverSocket.accept();
try
{
//接受客户端信息
BufferedReader in=new BufferedReader(new InputStreamReader(client.getInputStream(),"UTF-8"));
String str=in.readLine();
System.out.println("read: "+str);
//向服务器发送消息
PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream(),"UTF-8")),true);
out.println("return "+str);
in.close();
out.close();
}catch(Exception ex)
{
System.out.println(ex.getMessage());
ex.printStackTrace();
}
finally
{
client.close();
System.out.println("close");
}
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
public static void main(String [] args)
{
Thread desktopServerThread=new Thread(new AndroidServer());
desktopServerThread.start();
}
}
手机端:
package net.testSocket; import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
//客户端的实现
public class TestSocket extends Activity {
private TextView text1;
private Button but1;
private EditText edit1;
private final String DEBUG_TAG="mySocketAct"; public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); text1=(TextView)findViewById(R.id.text1);
but1=(Button)findViewById(R.id.but1);
edit1=(EditText)findViewById(R.id.edit); but1.setOnClickListener(new Button.OnClickListener()
{
@Override
public void onClick(View v) {
Socket socket=null;
String mesg=edit1.getText().toString()+"\r\n";
edit1.setText("");
Log.e("dddd", "sent id"); try {
socket=new Socket("192.168.0.178",54321);
//向服务器发送信息
PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF-8")),true);
out.println(mesg); //接受服务器的信息
BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
String mstr=br.readLine();
if(mstr!=null)
{
text1.setText(mstr);
}else
{
text1.setText("数据错误");
}
out.close();
br.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch(Exception e)
{
Log.e(DEBUG_TAG,e.toString());
}
}
});
}
}
注意事项:
请保证手机和电脑连载同一个局域网中,并且能够相互ping通。并且端口号没有被占用。
另外,一定要保证电脑的防火墙是关闭的。没有关闭的,请自己去关闭吧。不然。真的没得玩。会一直提示连接超时的。
为了防止中文乱码,请指定传输数据的格式。