这两天突然玩java,发现有点意思.以前不太喜欢java,主要是在许多时候做客户端并不方便,后来在许多应用方面,发现java还是很强悍的.大有相见恨晚之意.记得以前有位大师说是每年至少了解一门语言,这样方便你了解其它语言的特性,并与现在的语种进行比较.
java是一种网络语言,做网络编程应该很有意思吧.
下面是一个很简单的java的socket示例.
server端在5678端口开了服务,并进入读取客户端循环中.
package mysktserver; import java.io.*; import java.net.*; public class Main { public static void main(String[] args) throws IOException { ServerSocket server = new ServerSocket(5678); Socket client = server.accept(); BufferedReader in = new BufferedReader( new InputStreamReader(client.getInputStream())); PrintWriter out = new PrintWriter(client.getOutputStream()); while(true) { String str = in.readLine(); System.out.println(str); out.println("has receive ..."); out.flush(); if (str.equals("end")) { break; } client.close(); } } }
|
客户端连接到本地的5678端口.
package mysktclient; import java.net.*; import java.io.*; public class Main { static Socket server; public static void main(String[] args) throws Exception { server = new Socket(InetAddress.getLocalHost(),5678); BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream())); PrintWriter out = new PrintWriter(server.getOutputStream()); BufferedReader wt = new BufferedReader(new InputStreamReader(System.in)); while(true) { String str = wt.readLine(); out.println(str); out.flush(); if(str.equals("end")) { break; } System.out.println(in.readLine()); } server.close(); } }
|
这个例子只是简单的做出java做socket编程的便利性.以后的日子将会更加深入.
阅读(1062) | 评论(0) | 转发(0) |