在Android中通过Socket来来连接服务器,是一种比较简单的网络连接方式,虽然现在使用的不多,但某些场合还是很方便的,这里总结一下基本的写法。
客户端:
try { Socket socket = new Socket(host, port); socket.setSoTimeout(6 * 1000); PrintWriter printWriter = new PrintWriter( socket.getOutputStream(), true); printWriter.println("socket test"); printWriter.flush(); BufferedReader reader = new BufferedReader( new InputStreamReader(socket.getInputStream(), "GBK")); revMsg = reader.readLine(); if (TextUtils.isEmpty(revMsg)) { revMsg = "Server Error"; } printWriter.close(); reader.close(); socket.close(); return revMsg; } catch (Exception e) { e.printStackTrace(); revMsg = "Server Error"; }
import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(8888); while (true) { Socket socket = serverSocket.accept(); new ServerThread(socket); } } catch (Exception e) { e.printStackTrace(); } } }
import java.io.BufferedReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; class ServerThread extends Thread { private Socket socket; private BufferedReader bufferedReader; private PrintWriter printWriter; public ServerThread(Socket socket) throws IOException { this.socket = socket; bufferedReader = new BufferedReader(new InputStreamReader( socket.getInputStream())); printWriter = new PrintWriter(socket.getOutputStream(), true); System.out.println("Client(" + getName() + ") connected..."); start(); } @Override public void run() { try { String line = bufferedReader.readLine(); if (!line.equals("exit")) { System.out.println("Client(" + getName() + ") say: " + line); WriteToTxt(line + "\r\n","/local/data.txt"); printWriter.println("Receive Success!"); } printWriter.close(); bufferedReader.close(); socket.close(); } catch (IOException e) { } } private void WriteToTxt(String str, String path) { try { FileWriter writer = new FileWriter(path, true); writer.write(str); writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
Demo很简单。
以上。
原文地址:http://blog.csdn.net/eclipsexys/article/details/39551735