@linux1s1s
2017-01-22T17:18:41.000000Z
字数 5609
阅读 2493
AndroidHttp
2015-05
1: 创建客户端套接字(指定服务器端IP地址与端口号)
2: 连接(Android 创建Socket时会自动连接)
3: 与服务器端进行通信
4: 关闭套接字
- 客户端先建立连接后先获得输出流,然后再获得输入流。不然活有EOFException的异常。
- 中间的管道连接是通过InputStream/OutputStream流实现的。
- 一旦管道建立起来可进行通信 。
- 关闭管道的同时意味着关闭Socket 。
- 当对同一个Socket创建重复管道时会异常。
try {
//连接服务器 并设置连接超时为5秒
socket = new Socket();
socket.connect(new InetSocketAddress("1.1.9.30", 30000), 5000);
//先获取输出流
OutputStream ou = socket.getOutputStream();
//再获取输入流
BufferedReader bff = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
//读取发来服务器信息
String line = null;
buffer="";
while ((line = bff.readLine()) != null) {
buffer = line + buffer;
}
//向输出流写入信息,即向服务器发送信息
ou.write("android 客户端".getBytes("gbk"));
ou.flush();
bundle.putString("msg", buffer.toString());
msg.setData(bundle);
//发送消息 修改UI线程中的组件
myHandler.sendMessage(msg);
} catch (IOException e) {
e.printStackTrace();
}finally
{
//关闭各种输入输出流以及套接字
bff.close();
ou.close();
socket.close();
}
1: 创建服务器端套接字并绑定到一个端口上(0-1023是系统预留的,最好大约1024)
2: 套接字设置监听模式等待连接请求
3: 接受连接请求后进行通信
4: 返回,等待赢一个连接请求
- 服务器端首先得到输入流,然后将输入流信息输出到其各个客户端
- 中间的管道连接是通过InputStream/OutputStream流实现的。
- 一旦管道建立起来可进行通信 。
- 关闭管道的同时意味着关闭Socket 。
- 当对同一个Socket创建重复管道时会异常。
public class AndroidService {
public static void main(String[] args) throws IOException {
ServerSocket serivce = new ServerSocket(30000);
while (true) {
//等待客户端连接
Socket socket = serivce.accept();
new Thread(new AndroidRunable(socket)).start();
}
}
}
String str = "hello world!";
try {
// 首先得到输入流,将输入流读入内存
input = socket.getInputStream();
BufferedReader bff = new BufferedReader(
new InputStreamReader(input));
//然后再向客户端发送信息
output = socket.getOutputStream();
output.write(str.getBytes("gbk"));
output.flush();
//半关闭socket
socket.shutdownOutput();
//获取客户端的信息
while ((line = bff.readLine()) != null) {
System.out.print(line); //这里仅仅是测试使用的,接收到客户端的信息打印出来,有点无聊\(^o^)/~
}
} catch (IOException e) {
e.printStackTrace();
}
finally
{
//关闭各种输入输出流以及套接字
output.close();
bff.close();
input.close();
socket.close();
}
public class SocketActivity extends Activity {
EditText editText = null;
Button sendButton = null;
TextView display = null;
Socket client = null;
MyHandler myHandler;
DataOutputStream dout;
DataInputStream din;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.clientsocket);
editText = (EditText) findViewById(R.id.message);
sendButton = (Button) findViewById(R.id.send);
display = (TextView) findViewById(R.id.display);
sendButton.setOnClickListener(listener);
try {
client = new Socket("192.168.0.120", 50003);
dout = new DataOutputStream(client.getOutputStream());
din = new DataInputStream(client.getInputStream());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myHandler = new MyHandler();
MyThread m = new MyThread();
m.start();
}
class MyHandler extends Handler {
public MyHandler() {
}
// 子类必须重写此方法,接受数据
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
Log.d("MyHandler", "handleMessage......");
super.handleMessage(msg);
// 此处可以更新UI
if (client != null && client.isConnected()) {
Log.i("handler..", "*-----*");
try {
dout.writeUTF("connect...");
String message = din.readUTF();
if (!message.equals(""))
display.setText(display.getText().toString() + "\n"
+ "服务器发来的消息--:" + message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class MyThread extends Thread {
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Message msg = new Message();
SocketActivity.this.myHandler.sendMessage(msg);
}
}
}
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String sendText = editText.getText().toString();
try {
// din = new DataInputStream(client.getInputStream());
dout.writeUTF(sendText);
/*
* display.setText(display.getText().toString() + "\n" +
* "服务器发来的消息:" + din.readUTF());
*/
/*
* display.setText(display.getText().toString() + "\n" +
* "服务器发来的消息--:" + din.readUTF());
*/
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
}
public class Server {
static ServerSocket aServerSocket = null; // Server Socet.
DataInputStream aDataInput = null; // Server input Stream that to
// receive msg from client.
DataOutputStream aDataOutput = null; // Server output Stream that to
static ArrayList list = new ArrayList();
public static void main(String[] args) {
try {
aServerSocket = new ServerSocket(50003); // listen 8888 port.
System.out.println("already listen 50003 port.");
} catch (Exception e) {
e.printStackTrace();
}
int num = 0;
while (num < 10) {
Socket aSessionSoket = null;
try {
aSessionSoket = aServerSocket.accept();
MyThread thread = new Server().new MyThread(aSessionSoket);
thread.start();
num = list.size();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
class MyThread extends Thread {
Socket aSessionSoket = null;
public MyThread(Socket socket) {
aSessionSoket = socket;
}
public void run() {
try {
aDataInput = new DataInputStream(aSessionSoket.getInputStream());
aDataOutput = new DataOutputStream(aSessionSoket
.getOutputStream());
list.add(aDataOutput);
while (true) {
String msg = aDataInput.readUTF(); // read msg.
if (!msg.equals("connect...")) {
System.out.println("ip: "
+ aSessionSoket.getInetAddress());// ip.
System.out.println("receive msg: " + msg);
for (int i = 0; i < list.size(); i++) {
DataOutputStream output = (DataOutputStream) list
.get(i);
output.writeUTF(msg + "----" + list.size());
}
if (msg.equals("end"))
break;
}
aDataOutput.writeUTF("");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
aDataInput.close();
if (aDataOutput != null)
aDataOutput.close();
list.remove(aDataOutput);
aSessionSoket.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
}
附注:以上只是对Android的Socket编程的大致思路和过程,其中缺少了对于InputStream/OututStream 的异常处理,连接超时等处理。
本文参考:http://duguyidao.iteye.com/blog/1069736