手机与电脑 socket通信

来源:互联网 发布:类似灵魂摆渡的网络剧 编辑:程序博客网 时间:2024/04/28 19:08

安卓手机与电脑Java客户端之间的socket通信,最终效果图如下:


下面给出代码:


电脑端:


public class Server {   public static JTextArea textarea=new JTextArea();   JTextField text;        ActionListener l=new ActionListener() { @Overridepublic void actionPerformed(ActionEvent e) {Send send=new Send();send.go();}};public static void main(String[] args) {     Server s=new Server();     Accept a=new Accept();     Thread t=new Thread(a);     s.go();     t.run();        }public void go(){JFrame frame=new JFrame();frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);JPanel panel=new JPanel();JButton button=new JButton("发送");button.addActionListener(l);textarea =new JTextArea(10,20);textarea.setLineWrap(true);text=new JTextField();text.addKeyListener(new KeyAdapter(){      public void keyPressed(KeyEvent e)         {           if(e.getKeyChar()==KeyEvent.VK_ENTER )   //按回车键执行相应操作;        {          Send send =new Send();         send.go();       }      }    });panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));JScrollPane scroller = new JScrollPane(textarea);scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);panel.add(scroller);panel.add(text);frame.getContentPane().add(BorderLayout.CENTER,panel);frame.getContentPane().add(BorderLayout.SOUTH,button);frame.setSize(300,300);frame.setVisible(true);}class Send{public void go(){String str=text.getText().toString();if(str.equals("")||str==null)        {    text.setText("请输入后再发送!");       }     else{    textarea.append("电脑->手机:\n"+str+"\n");try{Socket s=new Socket("192.168.191.3",20000);DataOutputStream out=new DataOutputStream(s.getOutputStream());                 out.writeUTF(str);                 out.flush(); }catch(IOException ex){text.setText("没连上");}    text.setText(null);    }}}}public class Accept implements Runnable {@Overridepublic void run() {try{ServerSocket server =new ServerSocket(23000);while(true){Socket socket=server.accept();DataInputStream input=new DataInputStream(socket.getInputStream());String strget=input.readUTF();   Server.textarea.append("手机->电脑:\n"+strget+"\n");} }catch(IOException e){e.printStackTrace();}}}



手机端:

public class MainActivity extends Activity {EditText et=null;//编辑框Button bsend=null;//发送按钮LinearLayout ll;//布局protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);et=(EditText)findViewById(R.id.editText1);bsend=(Button)findViewById(R.id.button1);ll=(LinearLayout)findViewById(R.id.ll);bsend.setText("发送");bsend.setOnClickListener(new Button.OnClickListener() {           public void onClick(View v) {        String str=et.getText().toString();        if(str.equals("")||str==null)        {  Toast.makeText(MainActivity.this, "请输入信息后再发送", Toast.LENGTH_SHORT).show();     }  else{  try {                                      Socket socket = new Socket("192.168.191.1",23000);                                                DataOutputStream out=new DataOutputStream(socket.getOutputStream());                   out.writeUTF(str);                   out.flush();                   AddText a=new AddText();                   a.add("手机->电脑:\n"+str+"\n",-65536);                   et.setText("");                   }                                       catch (IOException ex) {                  Toast.makeText(MainActivity.this, "无法获取Ip!", Toast.LENGTH_SHORT).show();                   }  }                         }       });Service s=new Service();Thread t=new Thread(s);t.start();}public boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.main, menu);return true;}    class AddText{String str=null;int color=0;public void add(String str,int color){  TextView show =new TextView(MainActivity.this);      ll.addView(show);      show.setTextSize(15);      show.setTextColor(color);  show.setText(str);}}    public Handler mHandler = new Handler() { public void handleMessage(Message msg) {super.handleMessage(msg);Bundle b = msg.getData();   AddText a1=new AddText();        a1.add("电脑->手机:\n"+msg.obj.toString()+"\n",-16776961);            }  };protected void onDestroy() {super.onDestroy();android.os.Process.killProcess(android.os.Process.myPid());}        class Service implements Runnable{    public void run() {    try{        ServerSocket server=new ServerSocket(20000);        while(true){             Socket socket = server.accept();                    DataInputStream input=new DataInputStream(socket.getInputStream());             Message message = new Message();             Bundle b = new Bundle();             message.obj=input.readUTF();             message.setData(b);              MainActivity.this.mHandler.sendMessage(message);             }        } catch (IOException e) {              e.printStackTrace();              }             }    } }



1 0