java-Socket编程

分为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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值