4,360
社区成员
发帖
与我相关
我的任务
分享
package com.zlb.control_computer_01;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class MainActivity {
public static void main(String[] args) {
try {
ServerSocket server=new ServerSocket(9999);
while(true){
System.out.println("你尚未连接上客户端!");
Socket client=server.accept();
System.out.println("恭喜,已连接!");
OutputStream out=client.getOutputStream();
String msg="test";
out.write(msg.getBytes());
client.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.example.phone_test_01;
import java.io.InputStream;
import java.net.Socket;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void ButtonOnClick(View view)
{
TextView text=(TextView)findViewById(R.id.text);
try {
text.setText("等待建立Socket!");
Socket socket=new Socket("192.168.1.106",9999);
text.setText("Socket连接已完成!");
InputStream in= socket.getInputStream();
byte[] buffer=new byte[in.available()];
in.read(buffer);
String msg=new String(buffer);
text.setText(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.phone_test_01"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<!--允许应用程序完全使用网络-->
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.phone_test_01.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="目前尚未连接电脑!" />
<Button
android:id="@+id/connect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="ButtonOnClick"
android:text="连接电脑!"/>
</LinearLayout>