Java的socket简单语法实例以及多线程

1.服务期实现以及多线程加入

public class Sever
{

	public static void main(String[] args) throws Exception
	{
		ServerSocket sc = new ServerSocket(520);
		
	
		while(true){
			//获得监听套接字
			Socket ss = sc.accept();
			
			//创建一个线程,里面的类必须是接口Runnable的实现类,其中必须实现一个run方法
			new Thread(new Shixianjiekou(ss)).start();

		}

	}

}

2.客户端的实现

public class Client
{

	public static void main(String[] args) throws Exception
	{
		Socket ss = new Socket("localhost", 520);
		InputStream in = ss.getInputStream();
		OutputStream out = ss.getOutputStream();
		
		
		byte[] b = new byte[1024];
		int num = in.read(b);
		String string = new String(b,0,num);
		System.out.println(string);

	}

}

3.多线程的接口实现类

public class Shixianjiekou implements Runnable
{
	Socket ss;
	
	public Shixianjiekou(Socket ss)
	{
		this.ss = ss;
	}
	
	
	
	
	@Override
	public void run(){	
		try{
			//获得输入、输出流
			InputStream in = ss.getInputStream();
			OutputStream out = ss.getOutputStream();
			out.write("杨慧敏,我喜欢你".getBytes());
			
			}catch(Exception e){
				
			};
		
	}

}
发布了51 篇原创文章 · 获赞 9 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_43316411/article/details/88878191