Socket通信有两种方式,一种是基于TCP,另一种是基于UDP。本文是基于TCP的方式。废话不多说,直接上代码
手机端代码
package com.example.sockettest;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
private static final String TAG = "MainActivity";
private EditText mEditText;
private Button mButton;
private String sendMesg;
private Socket socket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditText = (EditText) this.findViewById(R.id.mEditText);
mButton = (Button) this.findViewById(R.id.mButton);
mButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
sendMesg = mEditText.getText().toString();
new Thread(new Runnable() {
@Override
public void run() {
try {
socket = new Socket("192.168.70.46", 12574);
//向服务器发送数据
PrintWriter send = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8")));
send.println(sendMesg);
send.flush();
//接受服务端数据
BufferedReader recv = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String recvMsg = recv.readLine();
if (recvMsg != null) {
// mRecvText.setText(recvMsg);
Log.e(TAG,"返回的内容是:"+recvMsg);
} else {
// mRecvText.setText("Cannot receive data correctly.");
}
send.close();
recv.close();
socket.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}).start();
}
});
}
}
PC端代码(java)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class TestMain implements Runnable{
public static void main(String[] args) {
Thread myThread = new Thread(new TestMain());
myThread.start();
}
@Override
public void run() {
try {
@SuppressWarnings("resource")
ServerSocket serverSocket = new ServerSocket(12574);
while (true) {
Socket client = serverSocket.accept();
System.out.println("accept");
try {
//接收客户端的数据
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(),"utf-8"));
String str = in.readLine();
System.out.println("read:" + str);
//返回数据给客户端
PrintWriter pout = new PrintWriter(new OutputStreamWriter(client.getOutputStream(), "utf-8"));
pout.println("返回数据给客户端 " + "123456");
System.out.println("after send in server");
pout.close();
in.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
client.close();
System.out.println("close");
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
最后需要注意的是要在AndroidManifest.xml中需要添加网络权限