欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

教你轻松读懂Java中的Socket编程(1)(3)

来源: javaer 分享于  点击 39357 次 点评:44

附注一个例子

这里我们增加一个例子,使用socket实现一个回声服务器,就是服务器会将客户端发送过来的数据传回给客户端。代码很简单。

import java.io.*; import java.net.*; public class EchoServer { public static void main(String args) { // declaration section: // declare a server socket and a client socket for the server // declare an input and an output stream ServerSocket echoServer = null; String line; DataInputStream is; PrintStream os; Socket clientSocket = null; // Try to open a server socket on port 9999 // Note that we can't choose a port less than 1023 if we are not // privileged users (root) try { echoServer = new ServerSocket(9999); } catch (IOException e) { System.out.println(e); } // Create a socket object from the ServerSocket to listen and accept // connections. // Open input and output streams try { clientSocket = echoServer.accept; is = new DataInputStream(clientSocket.getInputStream); os = new PrintStream(clientSocket.getOutputStream); // As long as we receive data, echo that data back to the client. while (true) { line = is.readLine; os.println(line); } } catch (IOException e) { System.out.println(e); } } }

编译运行上面的代码,进行如下请求,就可以看到客户端请求携带的数据的内容。

15:00 $ curl http://127.0.0.1:9999/?111 GET /?111 HTTP/1.1 User-Agent: curl/7.37.1 Host: 127.0.0.1:9999 Accept: */*总结

进行客户端-服务器端编程还是比较有趣的,同时在Java中进行socket编程要比其他语言(如C)要简单快速编写。

java.net这个包里面包含了很多强大灵活的类供开发者进行网络编程,在进行网络编程中,建议使用这个包下面的API。同时Sun.*这个包也包含了很多的网络编程相关的类,但是不建议使用这个包下面的API,因为这个包可能会改变,另外这个包不能保证在所有的平台都有包含。




相关栏目:

用户点评