⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tcptest.java

📁 孙鑫JAVA从入门到精通配套练习程序。所有程序都实际运行过
💻 JAVA
字号:
//演示网络相关程序
import java.io.*;
import java.net.*;

public class NetTest extends Thread
{
	private Socket s;
	NetTest(Socket s)
	{
		this.s = s;
	}
	public void run()
	{
		try
		{
			InputStream is = s.getInputStream();
			OutputStream os = s.getOutputStream();
			byte[] data = new byte[100];
			int len = is.read(data);
			System.out.println(new String(data, 0, len));
			os.write("Hello, welcome".getBytes());
			is.close();
			os.close();
			s.close();
		}
		catch(IOException ex)
		{
			System.out.println(ex);
		}
	}
	public static void main(String[] args) throws IOException
	{
		if (args.length > 0)
		{
			//服务器端程序需先启动
			server();
		}
		else
		{
			client();
		}
	}
	//创建服务器端应用程序
	public static void server() throws IOException
	{
		ServerSocket ss = new ServerSocket(6000);
		while(true)
		{
			Socket s = ss.accept();
			new NetTest(s).start();
		}
		//ss.close();
	}
	
	//创建客户端应用程序
	public static void client() throws IOException
	{
		Socket s = new Socket(InetAddress.getByName(null), 6000);
		InputStream is = s.getInputStream();
		OutputStream os = s.getOutputStream();
		byte[] data = new byte[100];
		os.write("This is zhangshan".getBytes());
		int len = is.read(data);
		System.out.println(new String(data, 0, len));
		is.close();
		os.close();
		s.close();
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -