分类: 嵌入式
2011-10-18 12:57:40
public class JSocket implements Runnable {
private ServerSocket serverSocket;
private Socket client;
@Override
public void run() {
try {
serverSocket = new ServerSocket(8888);
while (true) {
client = serverSocket.accept();
System.out.println("accept");
try {
// 接收客户端信息
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(),"GBK"));
String str = in.readLine();
System.out.println("read:" + str);
// 向客户端发送信息
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())),true);
out.println("您刚刚发送了:" + str);
in.close();
out.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
client.close();
System.out.println("close");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Thread thread = new Thread(new JSocket());
thread.start();
}
}
2、Android客户端代码
public class AscActivity extends Activity {
private Button mButton;
private TextView mTextView;
private EditText mEditText;
private final String EBUG_TAG = "Activity01";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mButton = (Button) findViewById(R.id.Button01);
mTextView = (TextView) findViewById(R.id.TextView01);
mEditText = (EditText) findViewById(R.id.EditText01);
mButton.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
Socket socket = null;
String message = mEditText.getText().toString() + "\r\n";
try {
socket = new Socket("192.168.7.51", 8888);
// socket = new Socket("192.168.7.21", 8888);
// 向服务器发送信息
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream(),
"GBK")),
true);
System.out.println(message);
out.println(message);
// 接收服务器信息
BufferedReader br = new BufferedReader(
new InputStreamReader(socket.getInputStream(),
"GBK"));
String msg = br.readLine();
System.out.println(msg);
if (msg != null) {
mTextView.setText(msg);
} else {
mTextView.setText("数据错误");
}
out.close();
br.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
Log.e(EBUG_TAG, e.toString());
}
}
});
}
}