java-Socket编程

来源:互联网 发布:男朋友 短小 知乎 编辑:程序博客网 时间:2024/06/07 12:40

分为tcp和udp

tcp:

server

import java.net.*;import java.io.*;public class TestServerSocket {public static void main(String []args)throws Exception{ServerSocket ss=new ServerSocket(1234);while(true){Socket s=ss.accept();System.out.println("A Client!");InputStream is=s.getInputStream();BufferedReader rer=new BufferedReader(new InputStreamReader(is));String st=new String();while((st=rer.readLine())!=null){System.out.println("   "+st);Thread.sleep(1000);}}}}

client

import java.net.*;import java.io.*;public class TestClient {private static int count=0; public static void main(String []args)throws Exception{Socket s=new Socket("127.0.0.1",1234);OutputStream os=s.getOutputStream();BufferedWriter wer=new BufferedWriter(new OutputStreamWriter(os));for(int i=0;i<100;i++){wer.write("Hello Server!  id:"+i+"\n");}wer.flush();wer.close();s.close();}}

udp:

server:

import java.net.*;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(1234);while(true){ds.receive(dp);String s=new String(buf,0,dp.getLength());long n=Long.parseLong(s);System.out.println(n);}}}

client:

import java.net.*;class TestUdpClient{public static void main(String []args)throws Exception{//byte[]buf=new String("Hello Server!").getBytes();long n=10000L;byte[] buf=Long.toString(n).getBytes();DatagramPacket dp=new DatagramPacket(buf,buf.length,new InetSocketAddress("127.0.0.1",1234));DatagramSocket ds=new DatagramSocket();ds.send(dp);ds.close();}}


0 0