Android:Socket基本使用

服务端

ServerSocket serverSocket = new ServerSocket(8688);
Socket client = serverSocket.accept();

//向客户端发送消息
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())));
pw.print("欢迎来到聊天室");
//从客户端接受消息
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = br.readLine();
Log.d("xl", str);

br.close();
pw.close();
client.close();

客户端

socket = new Socket("localhost", 8688);
Socket mClientSocket = socket;

//向服务端发送消息
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(mClientSocket.getOutputStream())),true);
pw.write("hahaha");

//从服务端接受消息
BufferedReader br = new BufferedReader(new InputStreamReader(mClientSocket.getInputStream()));
String s = br.readLine();

你可能感兴趣的:(Android:Socket基本使用)