这是一个用Java实现网络通信的例子,原理就是用Socket对象的输入和输出流实现接收和发送数据包。代码如下:
//MyClient.java
import java.net.*; import java.io.*; public class MyClient { public static void main(String[] args) { try { Socket s = new Socket("localhost", 8000); OutputStream os = s.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os); PrintWriter pw = new PrintWriter(osw, true); pw.println("zhuojiaoshou"); System.out.println("client send complete"); InputStream is = s.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String mess = br.readLine(); System.out.println("client receive complete"); System.out.println(mess); } catch(Exception e) { } } }
//MyServer.java
import java.net.*; import java.io.*; public class MyServer { public static void main(String[] args) { try { ServerSocket ss = new ServerSocket(8000); Socket s = ss.accept(); InputStream is = s.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String name = br.readLine(); System.out.println("server receive complete, " + name); OutputStream os = s.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os); PrintWriter pw = new PrintWriter(osw, true); pw.println("Welcome " + name); System.out.println("server write back complete"); } catch (Exception e) { e.printStackTrace(); } } }
第一步:先启动服务器端,打开一个8000端口(注意不要使用已经占用的端口,这样会抛出异常)。
第二步:启动客户端,地址可以使用“localhost”或者“127.0.0.1”(本地通信,若想在不同的主机上实现则需填入对方服务器的IP地址),设置跟服务器相同的端口号。
最后,使用输入输出流便可实现数据通信。