服务器端代码
public class Server implements Runnable { public void run() { try { //创建ServerSocket ServerSocket serverSocket = new ServerSocket(54321); while (true) { //接受客户端请求 Socket client = serverSocket.accept(); System.out.println("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("server message"); //关闭流 out.close(); in.close(); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } finally { //关闭 client.close(); System.out.println("close"); } } } catch (Exception e) { System.out.println(e.getMessage()); } } //main函数,开启服务器 public static void main(String a[]) { Thread desktopServerThread = new Thread(new Server()); desktopServerThread.start(); } }
android应用端:
UI
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/messageText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <EditText android:id="@+id/messageEdit" android:layout_width="match_parent" android:layout_height="wrap_content" > <requestFocus /> </EditText> <Button android:id="@+id/sendButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Button" /> </LinearLayout>
主页面
public class MainActivity extends Activity { private EditText messageEdit = null; private Button sendButton = null; private TextView messageText = null; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); messageEdit = (EditText)findViewById(R.id.messageEdit); messageText = (TextView)findViewById(R.id.messageText); sendButton = (Button)findViewById(R.id.sendButton); sendButton.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub Socket socket = null; String str = messageEdit.getText().toString(); try { //创建Socket socket = new Socket("10.200.194.29", 54321); //向服务器发送消息 PrintWriter out = new PrintWriter(new PrintWriter(socket.getOutputStream()), true); out.println(str); //接收来自服务器的消息 BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); String msg = br.readLine(); if(msg != null){ messageText.setText(msg); } else{ messageText.setText("数据错误!"); } //关闭流 out.close(); br.close(); //关闭Socket socket.close(); } catch (Exception e) { // TODO: handle exception System.out.println(e.toString()); } } }); } }
运行截图