新建JAVA project 服务端
package com.k.server;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Servers implements Runnable{
public void run() {
try {
ServerSocket serverSocket=new ServerSocket(54330);//监听端口
while(true)
{
System.out.println("等待接收用户连接:");
//接受客户端请求
Socket client=serverSocket.accept();
try
{
//接受客户端信息
BufferedReader in=new BufferedReader(new InputStreamReader(client.getInputStream()));
String str=in.readLine();
System.out.println("read: "+str);
//向服务器发送消息
PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())),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 t ;
t = new Thread(new Servers());
t.start(); //启动线程
}
}
客户端
//客户端的实现
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("10.0.2.2",54330);//模拟器IP 10.0.2.2
//向客户端发送信息
PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),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());
}
}
});
}
}