client.java

来自「C/S模型」· Java 代码 · 共 64 行

JAVA
64
字号
import java.net.*;
import java.io.*;

public class Client
{

	Socket clientSocket;
	PrintStream out;
	BufferedReader in;
	
	Client()
	{	
		try
		{
			clientSocket = new Socket("127.0.0.1",1002);
			out=new PrintStream(clientSocket.getOutputStream()); //往socket写
			in=new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); //从socket读
		}
		catch (UnknownHostException ue)
		{
			System.err.println("Unidentified hostname");
			System.exit(1);
		}
		catch (IOException e)
		{
			System.err.println("Couldn't get i/o");
			System.exit(1);
		}

	

		try
		{
		//一一交互进行
		BufferedReader stdin=new BufferedReader(new InputStreamReader((System.in))); //接受本地输入
		while (true)
		{
			String from=in.readLine();  //从socket读
			System.out.println(from); //打印提示信息
			if (from.equals("Welcome!!"))
			{continue;}
			else
			{
			String to=stdin.readLine();  //接受登录--用来和服务器交互的

			if (to.equals("Bye"))
			{
				break;
			}
			out.println(to); //往socket写,以供服务器判断
			}		
			}
		out.close();
		in.close();
		stdin.close();
		}catch(Exception e){}
	}
	
	public static void main(String[] args) throws IOException 
	{
		new Client();
	}
}

⌨️ 快捷键说明

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