android 里使用Socket进行发送消息案例

猜拳 源码
http://www.eoeandroid.com/thread-114907-1-1.html

自己实现的Android曲线图
http://www.eoeandroid.com/thread-207218-1-1.html

android游戏物理引擎源码
http://www.eoeandroid.com/thread-207445-1-1.html

socketServer类

package com.socket.server;
 
import java.io.*;
import java.net.*;
 
import android.content.Context;
import android.content.Intent;
 
public class SocketServer {
 
ServerSocket sever;
Context context;
 
public SocketServer(Context context, int port) {
try {
//实例化ServerSocket传入端口号
sever = new ServerSocket(port);
this.context = context;
} catch (IOException e) {
e.printStackTrace();
}
}
 
public void ControlActionAnswerMsg(String str) {
final Intent intent = new Intent();
intent.setAction("SOCKET_ACTION");
intent.putExtra("message", str);
context.sendBroadcast(intent);
}
 
public void beginListen() {
//将socket监听放入线程中,防止影响主线程操作
new Thread() {
public void run() {
//因为是不断监听的过程,所以采用死循环
while (true) {
try {
//这里是做监听操作
final Socket socket = sever.accept();
 
BufferedReader in;
try {
//监听到消息后这里读取流信息
in = new BufferedReader(new InputStreamReader(
socket.getInputStream(), "UTF-8"));
//将流信息放入PrintWriter中,然后读出来即可
PrintWriter out = new PrintWriter(
socket.getOutputStream());
while (!socket.isClosed()) {
String str;
//读出字符串
str = in.readLine();
out.println("Hello!world!! " + str);
out.flush();
if (str == null || str.equals("end"))
break;
System.out.println(str);
ControlActionAnswerMsg(str);
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
 
}
}.start();
}
}

ClientSocket类

package com.socket.pc;
import java.io.*;
import java.net.*;
public class ClientSocket {
 static Socket client;
 public ClientSocket(String site, int port) {
  try {
   //实例化socket传入ip和端口号,两边端口号要统一
   client = new Socket(site, port);
   System.out.println("Client is created! site:" + site + " port:"
     + port);
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
 public String sendMsg(String msg) {
  try {
   // BufferedReader in = new BufferedReader(new InputStreamReader(
   // client.getInputStream()));
   //将字符串转成输出流然后发送出去
   PrintWriter out = new PrintWriter(client.getOutputStream());
   out.println(msg);
   out.flush();
   // return in.readLine();
  } catch (IOException e) {
   e.printStackTrace();
  }
  return "";
 }
 public void closeSocket() {
  try {
   client.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

服务端与客户端源码

 

posted on 2012-10-17 13:58  nuliniao  阅读(3920)  评论(1编辑  收藏  举报