这里简单的总结一下TCP和UDP编程的写法,另外涉及到HttpUrlConnection的用法 。
TCP套接字
一、项目的流程如下说明:
1、客户输入一行字符,通过其套接字发送到服务器。 2、服务器从其连接的套接字中选取一行字符。 3、服务器将该行字符转换成大写并通过连接的套接字返回给客户 4、客户机从套接字中读取修改后的行,将其打印。
二、客户端的代码如下:
public class TCPClient { public static void main(String[] args) throws Exception { String sentence; String modifiedSentence; BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); Socket clientSocket = new Socket("localhost", 9999); DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); sentence = inFromUser.readLine(); outToServer.writeBytes(sentence + " "); modifiedSentence = inFromServer.readLine(); System.out.println("FROM SERVER: " + modifiedSentence); clientSocket.close(); } }
三、服务器的代码如下:
public class TCPServer { public static void main(String[] args) throws Exception { String clientSentence; String capitalzedSentence; ServerSocket serverSocket = new ServerSocket(9999); while (true) { Socket connectionSocket = serverSocket.accept(); BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); clientSentence = inFromClient.readLine(); capitalzedSentence = clientSentence.toUpperCase() + " "; outToClient.writeBytes(capitalzedSentence); } } }
四、运行的效果如下:
UDP套接字
项目的流程和上述的一样,这里不再赘述。
一、UDP客户端的代码:
public class UDPClient { public static void main(String[] args) throws Exception { BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); DatagramSocket clientSocket = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName("localhost"); byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; String sentence = inFromUser.readLine(); sendData = sentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9999); clientSocket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); String modifiedSentence = new String(receivePacket.getData()); System.out.println("FROM SERVER: " + modifiedSentence); clientSocket.close(); } }
二、UDP服务器的代码:
public class UDPServer { public static void main(String[] args) throws Exception { DatagramSocket serverSocket = new DatagramSocket(9999); byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; while (true) { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); String sentence = new String(receivePacket.getData()); InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); String capitalizedSentence = sentence.toLowerCase(); sendData = capitalizedSentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); } } }
和TCP不同的是,UDP可以先运行客户端,然后再运行服务器。这是因为当你执行客户端时,客户端进程并没有试图和服务器发起连接。
URLConnection的使用
一、从urlconnection中读取数据:
public class ReadFromUrlConn { public static void main(String[] args) throws Exception { URL url = new URL("https://www.baidu.com/"); URLConnection connection = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } }
二、HttpURLConnection的post请求数据
public void login() { HttpURLConnection httpURLConnection = null; InputStream inputStream = null; DataOutputStream out = null; try { URL url = new URL("http://localhost:9999/CsiiLearn/request/postTest.action"); httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("POST"); // 大小写是有区别的 httpURLConnection.setConnectTimeout(8000); httpURLConnection.setReadTimeout(8000); httpURLConnection.setDoOutput(true); // 这个需要在getOutputStream之前调用 out = new DataOutputStream(httpURLConnection.getOutputStream()); String params = "username=huxh&password=123456"; // post方法的请求参数 out.writeBytes(params); inputStream = httpURLConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder stringBuilder = new StringBuilder(); String line = ""; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line); } System.out.println("response: " + stringBuilder.toString()); } catch (Exception e) { e.printStackTrace(); } finally { try { inputStream.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }
一个多线程的例子
一、客户端的代码,请求得到一个随机产生的字符串
public class MainClient { public static void main(String[] args) { try { Socket socket = new Socket("localhost", 9999); BufferedReader inFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream())); String line = inFromServer.readLine(); System.out.println(line); } catch (IOException e) { e.printStackTrace(); } } }
二、服务器的代码,服务于客户端的请求
public class MainServer { public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(9999); ExecutorService executorService = Executors.newFixedThreadPool(10); while (true) { Socket socket = serverSocket.accept(); System.out.println("request has accept"); executorService.execute(new MulitpleThread(socket)); } } catch (Exception e) { e.printStackTrace(); } } }
三、服务器开启的服务线程
public class MulitpleThread implements Runnable { private Socket socket; MulitpleThread(Socket socket) { this.socket = socket; } @Override public void run() { try { DataOutputStream out = new DataOutputStream(socket.getOutputStream()); out.writeBytes("L。 " + new Random().nextInt(10)); socket.close(); // 这个是需要的,要不然客户端没有得到数据。 } catch (Exception e) { e.printStackTrace(); } } }