android中利用Socket实现手机客户端与PC端进行通信
服务器端:[java]
<span style="font-size:18px">import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer extends Thread{
public void run(){
Socket client;
String msg="";
try {
while(true){
client=responseSocket();
while(true){
msg=receiveMsg(client);
System.out.println("收到客户端消息:"+msg);
sendMsg(client,msg);
if(true){
break;
}
}
closeSocket(client);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static final int PORT=9999;
ServerSocket ss;
BufferedWriter bw;
BufferedReader br;
public void createSocket() throws IOException{
ss=new ServerSocket(PORT);
System.out.println("服务器已经开启······");
}
public Socket responseSocket() throws IOException{
Socket client=ss.accept();
System.out.println("客户端已经连接······");
return client;
}
public void closeSocket(Socket s) throws IOException{
br.close();
bw.close();
s.close();
System.out.println("客户端已经关闭······");
}
public void sendMsg(Socket s,String msg) throws IOException{
bw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
bw.write(msg+"\n");
bw.flush();
}
public String receiveMsg(Socket s) throws IOException{
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
String msg=br.readLine();
System.out.println("服务器收到客户端消息:"+msg);
return msg;
}
public SocketServer() throws IOException{
createSocket();
}
public static void main(String args[]) throws IOException{
SocketServer ss=new SocketServer();
if(ss!=null){
ss.start();
}
}
}
</span>
Android客户端:
[java]
<span style="font-size:18px">package com.colorful.socket;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class SocketClient extends Activity {
TextView tv;
EditText et;
Button btn;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
public void init(){
et=(EditText)findViewById(R.id.et);
btn=(Button)findViewById(R.id.btn);
tv=(TextView)findViewById(R.id.tv);
btn.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
&n
补充:移动开发 , Android ,