android Socket

新建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());
}
}        
        });
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值