开发学院手机开发Android 开发 Android 模拟器和PC用 sockets 通讯 阅读

Android 模拟器和PC用 sockets 通讯

 2010-03-26 06:02:00 来源:WEB开发网   
核心提示:mTextView=(TextView)findViewById(R.id.TextView01); mEditText=(EditText)findViewById(R.id.EditText01); //登陆 mButton.setOnClickListener(new OnClickListener() { pu
mTextView=(TextView)findViewById(R.id.TextView01); mEditText=(EditText)findViewById(R.id.EditText01); //登陆 mButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Socket socket = null; String message = mEditText.getText().toString() + " "; try { //创建Socket socket = new Socket("116.29.27.138",5554); //查看本机IP,每次开机都不同 //socket=new Socket("192.168.1.110",50000); //向服务器发送消息 PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true); out.println(message); //接收来自服务器的消息 BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); String msg = br.readLine(); if ( msg != null ) { mTextView.setText(msg); } else { mTextView.setText("数据错误!"); } //关闭流 out.close(); br.close(); //关闭Socket socket.close(); } catch (Exception e) { // TODO: handle exception Log.e(DEBUG_TAG, e.toString()); } } }); } }

服务器端代码:

Java代码

package com.yarin.android.Examples_08_04;

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;

public class Server implements Runnable

{

public void run()

{

try

{

//创建ServerSocket

ServerSocket serverSocket = new ServerSocket(5554);

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);

上一页  1 2 3 4  下一页

Tags:Android 模拟器 PC

编辑录入:coldstar [复制链接] [打 印]
[]
  • 好
  • 好的评价 如果觉得好,就请您
      0%(0)
  • 差
  • 差的评价 如果觉得差,就请您
      0%(0)
赞助商链接