java網路編程小結1

來源:互聯網
上載者:User

1 基本的tcp網路編程模式
   首先是server端,server端用的是serversocket,

 

import java.net.*;
import java.io.*;

public class TCPServer {
 public static void main(String[] args) throws Exception {
  ServerSocket ss = new ServerSocket(6666);
  while(true) {

       Socket s=ss.accept();

        DataInputStream dis=new DataInputStream(s.getInputStream());  

      System.out.println(dis.readUTF());
   dis.close();
   s.close();
  }
 }
}

 

   用戶端
   

import java.net.*;
import java.io.*;

public class TCPClient {
 public static void main(String[] args) throws Exception {
  Socket s = new Socket("127.0.0.1", 6666);
  OutputStream os = s.getOutputStream();
  DataOutputStream dos = new DataOutputStream(os);
  Thread.sleep(30000);
  dos.writeUTF("hello server!");
  dos.flush();
  dos.close();
  s.close();
 }
}

  對用戶端來說,是output輸出資料流到服務端.

 

2 下面的程式,可以通過服務端把用戶端的ip連接埠等輸出給用戶端
   

import java.net.*;
import java.io.*;

public class TestServer {
 public static void main(String args[]) {
  try {  
   ServerSocket s = new ServerSocket(8888);
   while (true) {
    Socket s1 = s.accept();
    OutputStream os = s1.getOutputStream();
    DataOutputStream dos = new DataOutputStream(os);
    dos.writeUTF("Hello," + s1.getInetAddress() +
      "port#" +s1.getPort() + "  bye-bye!");
    dos.close();
    s1.close();
   }
  }catch (IOException e) {
   e.printStackTrace();
   System.out.println("程式運行出錯:" + e);   
  }
 }
}

 

用戶端,則把服務端輸進來的資訊顯示
  

import java.net.*;
import java.io.*;

public class TestClient {
 public static void main(String args[]) {
  try {
   Socket s1 = new Socket("127.0.0.1", 8888);
   InputStream is = s1.getInputStream();
   DataInputStream dis = new DataInputStream(is);
   System.out.println(dis.readUTF());
   dis.close();
   s1.close();
  } catch (ConnectException connExc) {
   connExc.printStackTrace();
   System.err.println("伺服器串連失敗!");
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

 

 

3 下面的TCP則是客戶跟服務端各自發送一句話給對方.
  服務端:
   import java.io.*;
import java.net.*;
public class TestSockServer {
  public static void main(String[] args) {
    InputStream in = null;
    OutputStream out = null;
    try {
      ServerSocket ss = new ServerSocket(5888);
      Socket socket = ss.accept();
      in = socket.getInputStream();
      out = socket.getOutputStream();
      DataOutputStream dos = new DataOutputStream(out);
      DataInputStream dis = new DataInputStream(in);
      String s = null;
      if((s=dis.readUTF())!=null) {
       System.out.println(s);
       System.out.println("from: "+socket.getInetAddress());
       System.out.println("Port: "+socket.getPort());
     }
      dos.writeUTF("hi,hello");
      dis.close();
      dos.close();
      socket.close();
    } catch (IOException e) {e.printStackTrace();}
  }
}

   用戶端:
   import java.net.*;
import java.io.*;
public class TestSockClient {
  public static void main(String[] args) {
    InputStream is = null; OutputStream os = null;
    try {
      Socket socket = new Socket("localhost",5888);
      is = socket.getInputStream();
      os = socket.getOutputStream();
      DataInputStream dis = new DataInputStream(is);
      DataOutputStream dos = new DataOutputStream(os);
      dos.writeUTF("hey");
      String s = null;
      if((s=dis.readUTF())!=null);
       System.out.println(s);
      dos.close();
      dis.close();
      socket.close();
    } catch (UnknownHostException e) {
       e.printStackTrace();
    } catch (IOException e) {e.printStackTrace();}
  }
}

5 UDP中,注意datagrampacket的應用,下面的是用戶端發一訊息給服務端的
   public class TestUDPClient
{
 public static void main(String args[]) throws Exception
 {
  byte[] buf = (new String("Hello")).getBytes();

  Datagrampacket dp=new DatagramPacket(buf, buf.length,
              new InetSocketAddress("127.0.0.1", 5678)
              );
  DatagramSocket ds = new DatagramSocket(9999);
  ds.send(dp);
  ds.close();
 }

  服務端:
   

import java.net.*;

public class TestUDPServer
{
 public static void main(String args[]) throws Exception
 {
  byte buf[] = new byte[1024];
  DatagramPacket dp = new DatagramPacket(buf, buf.length);
  DatagramSocket ds = new DatagramSocket(5678);
  while(true)
  {
   ds.receive(dp);
   System.out.println(new String(buf,0,dp.getLength()));
  }
 }
}

  

  要注意的知識點是,如果是用戶端的其他類型的資料,在轉換時要注意,比如下面的例子傳一個長整型的到服務端:
用戶端:
  public class TestUDPClient
{
 public static void main(String args[]) throws Exception
 {
  long n = 10000L;
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  DataOutputStream dos = new DataOutputStream(baos);
  dos.writeLong(n);
  
  byte[] buf = baos.toByteArray();
System.out.println(buf.length);
  
  DatagramPacket dp = new DatagramPacket(buf, buf.length,
              new InetSocketAddress("127.0.0.1", 5678)
              );
  DatagramSocket ds = new DatagramSocket(9999);
  ds.send(dp);
  ds.close();
  
 }
}

服務端:
  

import java.net.*;
import java.io.*;

public class TestUDPServer
{
 public static void main(String args[]) throws Exception
 {
  byte buf[] = new byte[1024];
  DatagramPacket dp = new DatagramPacket(buf, buf.length);
  DatagramSocket ds = new DatagramSocket(5678);
  while(true)
  {
   ds.receive(dp);
   ByteArrayInputStream bais = new ByteArrayInputStream(buf);
   DataInputStream dis = new DataInputStream(bais);
   System.out.println(dis.readLong());
  }
 }
}

   
   

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.