一、服务器端,运行在PC机上
import java.io.*;
import java.net.*;
public class SimpleServer{
public static void main(String[] args) throws IOException{
ServerSocket ss=new ServerSocket(30000);
while(true){
Socket s=ss.accept();
OutputStream os=s.getOutputStream();
os.write("中国欢迎您".getBytes("GBK"));
os.close();
}
}
}
二、客户端,运行在Android设备上
1.在AndroidManifest.xml文件中添加权限
<uses-permission android:name="android.permission.INTERNET"/>
2.MainActivity.java
package com.example.shiyanshi.simpleclient;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
TextView txtShowData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtShowData= (TextView) findViewById(R.id.txtShowServerData);
txtSend=(EditText)findViewById(R.id.txtSend);
new Thread(){
@Override
public void run() {
super.run();
try {
Socket socket = new Socket("116.57.85.184", 30000);
InputStream inputStream = socket.getInputStream();
//以GBK编码方式构建BufferReader
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"GBK"));
String line = bufferedReader.readLine();
String string=new String(line.getBytes("GBK"));
txtShowData.setText(string);
bufferedReader.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}