新建两个Android项目:(例如SocketServer和SocketClient)
简单起见,Server端只发送一条信息,Client端只接收信息。
Server端代码:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
@Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(12333);
while (true) {
Socket socket = serverSocket.accept();
BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream()));
writer.write("Test Socket\r\n");
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
<