关闭

socket编程的代码之JAVA与android

标签: socketjava编程exceptionstringbutton
662人阅读 评论(0) 收藏 举报
分类:
Java代码:
  1. package com.wll.mysocket;import java.io.*;

  2. import java.net.ServerSocket;import java.net.Socket;

  3. public class myServer implements Runnable{public void run() {

  4. try {ServerSocket serverSocket=new ServerSocket(54321);

  5. while(true){System.out.println("接收用户连接:");

  6. //接受客户端请求
  7. Socket client=serverSocket.accept();

  8. System.out.println("accept:");

  9. try{

  10. //接受客户端信息

  11. BufferedReader in=new BufferedReader(new InputStreamReader(client.getInputStream()));

  12. String str=in.readLine();

  13. System.out.println("read:"+str);

  14. //向服务器发送消息

  15. PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())),true);

  16. out.println("Server Message:"+str);

  17. in.close();out.close();

  18. }catch(Exception ex){System.out.println(ex.getMessage());

  19. ex.printStackTrace();

  20. }finally{client.close();System.out.println("close");

  21. }
  22. }
  23. }
  24. catch (IOException e) {System.out.println(e.getMessage());

  25. }
  26. }
  27. public static void main(String [] args){Thread desktopServerThread=new Thread(new myServer());

  28. desktopServerThread.start();

  29. }
  30. }
复制代码

android代码:
  1. package com.wll.mysocket;import java.io.*;
  2. import java.net.Socket;
  3. import java.net.UnknownHostException;import android.*;
  4. //客户端的实现
  5. public class mySocketAct extends Activity {
  6. private TextView text1;private Button but1;private EditText edit1;private final StringDEBUG_TAG="mySocketAct";

  7. public void onCreate(Bundle savedInstanceState) {

  8. super.onCreate(savedInstanceState); setContentView(R.layout.main);

  9. text1=(TextView)findViewById(R.id.text1);

  10. but1=(Button)findViewById(R.id.but1);

  11. edit1=(EditText)findViewById(R.id.edit);

  12. but1.setOnClickListener(new Button.OnClickListener() {public void onClick(View v) {

  13. Socket socket=null;

  14. String mesg=edit1.getText().toString()+"\r\n";edit1.setText("");

  15. try {socket=new Socket("10.0.2.2",54321);

  16. //向服务器发送信息
  17. PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);out.println(mesg);

  18. //接受服务器的信息
  19. BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));

  20. String mstr=br.readLine();

  21. if(mstr!=null){text1.setText(mstr);

  22. }else{text1.setText("数据错误");

  23. }out.close();br.close();socket.close();

  24. } catch (UnknownHostException e) {e.printStackTrace();

  25. } catch (IOException e) {e.printStackTrace();}catch(Exception e){Log.e(DEBUG_TAG,e.toString());

  26. }
  27. }
  28. }
  29. );
  30. }
  31. }
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:109774次
    • 积分:1697
    • 等级:
    • 排名:千里之外
    • 原创:49篇
    • 转载:5篇
    • 译文:0篇
    • 评论:26条
    最新评论