java socket 示例代码

Java Socket 通信
本文介绍了一个使用 Java 实现客户端与服务器间 Socket 通信的例子。客户端通过 Socket 发送 XML 格式的请求,并接收服务器响应;服务器解析请求并返回简单 XML 响应。此外,还提供了一个简单的字符串交互示例。

示例1: 

//--------   test\Land\Client.java   --------  
  package   test.Land;  
   
  import   java.io.BufferedReader;  
  import   java.io.InputStreamReader;  
  import   java.net.Socket;  
   
  import   org.dom4j.Document;  
  import   org.dom4j.DocumentHelper;  
  import   org.dom4j.Element;  
  import   org.dom4j.io.OutputFormat;  
  import   org.dom4j.io.XMLWriter;  
   
  public   class   Client   {  
   
          public   static   void   main(String[]   args)   throws   Exception   {  
                  test();  
          }  
   
          public   static   void   test()   throws   Exception   {  
                  Socket   socket   =   new   Socket("localhost",   9999);  
   
                  //   发送请求  
                  Document   doc   =   DocumentHelper.createDocument();  
                  Element   root   =   doc.addElement("Class");  
                  Element   type   =   root.addElement("Types");  
                  Element   classes   =   root.addElement("Classes");  
                  Element   function   =   classes.addElement("FunctionLanding");  
                  type.addAttribute("type",   "String").addText("LandConn");  
                  classes.addAttribute("name",   "SQLParse");  
                  function.addAttribute("name",   "LandDemo");  
                  function.addElement("IPparam").addAttribute("type",   "String").addText("ClientIP");  
                  function.addElement("LNparam").addAttribute("type",   "String").addText("ClientName");  
                  function.addElement("ANparam").addAttribute("type",   "String").addText("ClientAccountNumber");  
                  function.addElement("PWparam").addAttribute("type",   "String").addText("ClientPassWord");  
                  function.addElement("Fparam").addAttribute("type",   "String").addText("Lflag");  
                  //   是否有缩进  
                  String   indent   =   "       ";  
                  //   是否产生新行(即一行一个元素)  
                  boolean   newline   =   true;  
                  XMLWriter   writer   =   new   XMLWriter(socket.getOutputStream(),   new   OutputFormat(indent,   newline,   "gb2312"));  
                  writer.write(doc);  
                  writer.flush();  
                  System.out.println("发送完毕");  
   
                  //   接收响应  
                  BufferedReader   br   =   new   BufferedReader(new   InputStreamReader(socket.getInputStream()));  
                  StringBuffer   sb   =   new   StringBuffer();  
                  String   line;  
                  //   接收数据,直至   socket   被对方   close(或者   shutdownOutput)  
                  while   ((line   =   br.readLine())   !=   null)   {  
                          sb.append(line);  
                  }  
                  System.out.println("接收到的内容:   "   +   sb.toString());  
   
                  socket.close();  
          }  
  }  
   
  //--------   test\Land\Server.java   --------  
  package   test.Land;  
   
  import   java.io.BufferedReader;  
  import   java.io.IOException;  
  import   java.io.InputStreamReader;  
  import   java.net.ServerSocket;  
  import   java.net.Socket;  
   
  import   org.dom4j.Document;  
  import   org.dom4j.DocumentHelper;  
  import   org.dom4j.Element;  
  import   org.dom4j.io.OutputFormat;  
  import   org.dom4j.io.XMLWriter;  
   
  public   class   Server   {  
   
          public   static   void   main(String[]   args)   throws   Exception   {  
                  test();  
          }  
   
          public   static   void   test()   throws   IOException   {  
                  ServerSocket   ss   =   new   ServerSocket(9999);  
                  Socket   socket   =   ss.accept();  
   
                  BufferedReader   br   =   new   BufferedReader(new   InputStreamReader(socket.getInputStream()));  
                  StringBuffer   sb   =   new   StringBuffer();  
                  String   line   =   null;  
                  //   接收数据,直至收到一行   "</Class>"  
                  while   (!"</Class>".equals(line   =   br.readLine()))   {  
                          sb.append(line);  
                  }  
                  sb.append("</Class>");  
                  System.out.println("接收到的内容:   "   +   sb.toString());  
   
                  //   返回信息  
                  Document   doc   =   DocumentHelper.createDocument();  
                  Element   root   =   doc.addElement("Class");  
                  Element   incept   =   root.addElement("incept");  
                  incept.addAttribute("type",   "boolean").addText(String.valueOf(true));  
                  String   lint   =   "       ";  
                  boolean   newline   =   true;  
                  XMLWriter   writer   =   new   XMLWriter(socket.getOutputStream(),   new   OutputFormat(lint,   newline,   "gb2312"));  
                  writer.write(doc);  
                  writer.flush();  
                  System.out.println("发送完毕");  
   
                  socket.close();  
                  ss.close();  
          }  
   
  }  

 

 

 

示例2:

String ip = "172.31.1.130";
  ip = "127.0.0.1";
  int port = 10004;
  try {
   Socket socket = new Socket(ip, port);
   socket.setSoTimeout(5539900);
   java.io.OutputStream out = socket.getOutputStream();
  
   byte[] date = "hello world".getBytes();
   out.write(data);
   out.flush();

   socket.shutdownOutput();

   byte[] buffer = new byte[1024];
   int len = -1;
   java.io.FileOutputStream fout = new java.io.FileOutputStream(
     "d:/response.xml");
   java.io.ByteArrayOutputStream bout = new java.io.ByteArrayOutputStream();

   java.io.InputStream in = socket.getInputStream();

   while ((len = in.read(buffer, 0, buffer.length)) > 0) {
    bout.write(buffer, 0, len);
   }
   in.close();
   bout.flush();
   bout.close();

   byte[] rdata = bout.toByteArray();
   // System.out.println("leen = " + (rdata.length - 32));
   System.out.println(new String(rdata));

   fout.write(rdata);
   fout.flush();
   fout.close();
   socket.close();
 
  } catch (UnknownHostException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
}


服务器端的


ServerSocket ss = new ServerSocket(8090);
  Socket socket=null;
  BufferedReader in;
  PrintWriter out;
 
  while (true)
  {
  socket = ss.accept();
  in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  out = new PrintWriter(socket.getOutputStream(),true);
  String line = in.readLine();
  out.println("you input is :" + line);
  out.close();
  in.close();
  socket.close();
  }

转载于:https://www.cnblogs.com/fenglive/archive/2010/04/12/1710210.html

import java.io.*; import java.net.*; import java.util.*; import java.lang.*; public class Server extends ServerSocket { private static ArrayList User_List = new ArrayList(); private static ArrayList Threader = new ArrayList(); private static LinkedList Message_Array = new LinkedList(); private static int Thread_Counter = 0; private static boolean isClear = true; protected static final int SERVER_PORT = 10000; protected FileOutputStream LOG_FILE = new FileOutputStream( "d:/connect.log", true); public Server() throws FileNotFoundException, IOException { super(SERVER_PORT); // append connection log // Calendar now = Calendar.getInstance(); // String str = "[" + now.getTime().toString() + // "] Accepted a connection"; // byte[] tmp = str.getBytes(); // LOG_FILE.write(tmp); try { Socket socket = accept(); while (true) { new ServerReaderThread(socket); new ServerWriterThread(socket); } } finally { close(); } } public static void main(String[] args) throws IOException { new Server(); } // --- CreateServerThread class ServerReaderThread extends Thread { private Socket client; private BufferedReader in; private PrintWriter out; private String Username; public ServerReaderThread(Socket s) throws IOException { client = s; in = new BufferedReader(new InputStreamReader(client .getInputStream())); out = new PrintWriter(client.getOutputStream(), true); start(); } public void run() { try { int flag = 0; Thread_Counter++; String line = in.readLine(); while (!line.equals("bye")) { out.println(line); line = in.readLine(); } out.println("--- See you, bye! ---"); // System.out.println("--- See you, bye! ---"); client.close(); } catch (IOException e) { } finally { try { client.close(); } catch (IOException e) { } Thread_Counter--; } } } // --- CreateServerThread class ServerWriterThread extends Thread { priva
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值