标签:
参考网上例子,写了个socket通信例子,运行可以成功
1.创建两个普通的java project,直接贴图如下
2.客户端代码如下
package client; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.Socket; public class Client { public static void main(String args[]) { try{ //创建客户端套接字 Socket socket = new Socket("127.0.0.1", 9999); //写入来自socket的输出流 Writer writer = new OutputStreamWriter(socket.getOutputStream()); writer.write("Hello world"); //刷新输出流 writer.flush(); writer.close(); socket.close(); }catch(Exception e) { e.printStackTrace(); } } }
3.服务器端代码如下
package server; import java.io.InputStreamReader; import java.io.Reader; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String args[]) { try { //创建一个ServerSocket,在端口号9999上监听客户端请求 ServerSocket serverSocket = new ServerSocket(9999); Socket socket = serverSocket.accept(); //获取来自socket的输入流 Reader reader = new InputStreamReader(socket.getInputStream()); char chars[] = new char[1024]; int len; StringBuilder builder = new StringBuilder(); while ((len = reader.read(chars)) != -1) { builder.append(new String(chars, 0, len)); } System.out.println("Receive from client message=: " + builder); reader.close(); socket.close(); serverSocket.close(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }
4.先run as 服务器端代码,使服务器运行起来,再运行客户端代码,运行结果如下
Receive from client message=: Hello world。
标签:
原文地址:http://my.oschina.net/u/2312022/blog/525904