In short:
The tcp connection used by Socket needs to be connected before sending data.
For the UDP connection used by datagram socket, the client does not need to connect the data first and can send it directly to the specified server.
DatagramSocket:
Client send (send data directly, no connection process):
protected void connectServerWithUDPSocket(Context context, String id) { DatagramSocket socket; try { //Create the datagram socket object and specify a port number. Note that if the client needs to receive the return data from the server, //You also need to use this port number to receive, so be sure to remember socket = new DatagramSocket(null); //Use InetAddress(Inet4Address).getByName to convert IP address to network address InetAddress serverAddress = null; mHost = Utils.getLocalIpStr(context); Log.d(TAG, "connectServerWithUDPSocket mHost =" + mHost); if (null == mHost) return; try { serverAddress = InetAddress.getByName(mHost); } catch (UnknownHostException e) { Log.d(TAG, "Server not found"); e.printStackTrace(); } //Inet4Address serverAddress = (Inet4Address) Inet4Address.getByName("192.168.1.32"); String str = id;//Set message to send byte data[] = str.getBytes();//Convert string str string to byte array //Create a datagram packet object to send data. //Parameter 1: data to be sent parameter 2: data length parameter 3: network address parameter 4: server slogans DatagramPacket packet = new DatagramPacket(data, data.length, serverAddress, PORT); try { socket.send(packet);//Send the data to the server. } catch (IOException e) { Log.d(TAG, "fail in send"); e.printStackTrace(); } Log.d(TAG, "socket.send------------------------"); } catch (SocketException e) { Log.i(TAG, "Failed to establish receive datagram"); e.printStackTrace(); } }
Server reception:
public void serverReceviedByUdp() { //Create a datagram socket object and specify the listening port. (datagram socket is used for UDP) DatagramSocket socket; try { socket = new DatagramSocket(PORT); //Create an array of byte type to hold the received data byte data[] = new byte[4 * 1024]; //Create a datagram packet object and specify the size of the datagram packet object DatagramPacket packet = new DatagramPacket(data, data.length); while (true) { //Read received data socket.receive(packet); //Convert the data sent by the client to a string. //A String method with three parameters. Parameter 1: packet parameter 2: starting position parameter 3: packet length String result = new String(packet.getData(), packet.getOffset(), packet.getLength()); Log.d(TAG, "service result = " + result); } } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Socket:
Server:
public class TcpServer { private static ServerSocket serverSocket; private static Socket socket; public static void startServer(){ if (serverSocket == null){ new Thread(new Runnable() { @Override public void run() { try { serverSocket = new ServerSocket(8080); Log.i("tcp" , "Server waiting to connect"); socket = serverSocket.accept(); Log.i("tcp" , "The client is connected"); InputStream inputStream = socket.getInputStream(); byte[] buffer = new byte[1024]; int len = -1; while ((len = inputStream.read(buffer)) != -1) { String data = new String(buffer, 0, len); Log.i("tcp" , "Data received from client-----------------------------:" + data); EventBus.getDefault().post(new MessageServer(data)); } } catch (IOException e) { e.printStackTrace(); }finally { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } socket = null; serverSocket = null; } } }).start(); } } public static void sendTcpMessage(final String msg){ if (socket != null && socket.isConnected()) { new Thread(new Runnable() { @Override public void run() { try { socket.getOutputStream().write(msg.getBytes()); socket.getOutputStream().flush(); } catch (IOException e) { e.printStackTrace(); } } }).start(); } } }
Client (you need to connect to the server before sending data):
public class TcpClient { public static Socket socket; public static void startClient(final String address ,final int port){ if (address == null){ return; } if (socket == null) { new Thread(new Runnable() { @Override public void run() { try { Log.i("tcp", "Start client"); socket = new Socket(address, port); Log.i("tcp", "Client connection successful"); PrintWriter pw = new PrintWriter(socket.getOutputStream()); InputStream inputStream = socket.getInputStream(); byte[] buffer = new byte[1024]; int len = -1; while ((len = inputStream.read(buffer)) != -1) { String data = new String(buffer, 0, len); Log.i("tcp", "Receive data from server---------------------------------------------:" + data); EventBus.getDefault().post(new MessageClient(data)); } Log.i("tcp", "Client disconnected"); pw.close(); } catch (Exception EE) { EE.printStackTrace(); Log.i("tcp", "Client cannot connect to server"); }finally { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } socket = null; } } }).start(); } } public static void sendTcpMessage(final String msg){ if (socket != null && socket.isConnected()) { new Thread(new Runnable() { @Override public void run() { try { socket.getOutputStream().write(msg.getBytes()); socket.getOutputStream().flush(); } catch (IOException e) { e.printStackTrace(); } } }).start(); } }
Reference resources: