在ADT建立一个JAVA工程,然后输入以下代码
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketTest {
public static void main(String args[])
throws IOException
{
ServerSocket ss=new ServerSocket(30001);
while(true )
{
Socket s=ss.accept();
OutputStream os=s.getOutputStream();
os.write( "Iwanttomarry\n".getBytes("utf-8" ));
os.close();
s.close();
}
}
}
然后建立安卓工程,输入以下代码:
public class MainActivity extends Activity {
EditText show;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout. activity_main);
show=(EditText)findViewById(R.id. show);
new Thread()
{
public void run()
{
try{
/*注意这里的IP是电脑私有地址*/
Socket socket= new Socket("192.168.1.104" ,30001);
BufferedReader br= new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line=br.readLine();
show.setText( "来自服务器的数据:" +line);
br.close();
socket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}.start();
}
}
然后在activity的layout里面放置一个edittext,
在manifest中设置入网权限,< uses-permission android:name ="android.permission.INTERNET"/>
先运行java程序,再运行android程序即可。