- Android socket编程
服务端:
1、指定端口对serversocket进行事例化
2、调用ServerSocket的accepet()方法防止在链接期间造成阻塞
3、获取底层Socket流对并对其进行读写操作
4、将数据封装成流
5、对Socket进行读写
6、关闭所有打开的输入输出流
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.ServerSocket;
import java.net.Socket;
public class Server implements Runnable{
pubulic void run(){
try{
ServerSocket serverSocket = new ServerSocket(66788);
while(ture){
Socket client = serverSocket.accept();
System.out.println("already accept");
try{
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = in.readLine();
System.out.println("read:" + str);
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())),ture);
out.println("serever message");
out.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());
}
}
public static void main(String a[]){
Thread desktopServerThread = new Thread(new Server());
desktopServerThread.start();
}
}
- 客户端
1、通过IP地址和端口实例化请求连接服务器
2、获取Socket上的流以进行读写
3、把流包进BufferedReader / PrintWriter 的事例;
4、对Socket进行读写
5、关闭打开流
public class Activity01 extends Activity{
private final String DEBUG_TAG = "Activity01";
private TextView mTextView = null;
private EditText mEditText = null;
private Button mButton = null;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContantView(R.layout.main);
mButton = (Button)findViewById(R.id.Button01);
mTextView = (TextView)findViewById(R.id.TextView01);
mEditText = (EditText)findViewById(R.id.EditText01);
mButton.setOnClickListener(new onClickListener()){
public void onClick(View v){
Socket socket null;
String message = mEditText.getText().toString() + "\r\n";
try{
socket = new Socket("192.168.1.6",66788);
PrintWriter out = new PrintWriter(newBufferedWriter(newOutputStreamWriter(socket.getOutputStream())),ture);
out,println(message);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg = br.readLine();
if(msg != null){
mTextView.setText(msg);
else{
mTextView.setText("数据错误");
}
out.close();
br.close();
socket.close();
}catch (Exception e){
Log.e(DEBUG_TAG,e.toString());
}
}
}
}
}
}