📄 server.java
字号:
/*
* Created on 2004-12-9
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
/**
* @author Administrator
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws IOException
{
String toClient;
PrintWriter out=null;
BufferedReader in=null;
boolean runable=true;
ServerSocket serverSocket=null;
try{
serverSocket=new ServerSocket(4000);
}catch(IOException e){
System.err.println("Can not build 4000 port");
System.exit(1);
}
Socket clientSocket=null;
try{
clientSocket=serverSocket.accept();
}catch(IOException e){
System.err.println("Failed to call on port 4000");
System.exit(1);
}
out=new PrintWriter(clientSocket.getOutputStream(),true);
in=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedReader stdIn=new BufferedReader(new InputStreamReader(System.in));
toClient="Hello,Welcome!";
out.println(toClient);
ReceiveClientThread readClientThread=new ReceiveClientThread(in);
readClientThread.start();
while(runable){
toClient=stdIn.readLine();
out.println(toClient);
if(toClient.equals("bye")) break;
runable=readClientThread.runable;
}
readClientThread.fromClient="Welcome come again!";
readClientThread.runable=false;
out.close();
in.close();
stdIn.close();
clientSocket.close();
serverSocket.close();
}
}
class ReceiveClientThread extends Thread{
BufferedReader in=null;
String fromClient="";
boolean runable=true;
public ReceiveClientThread(BufferedReader in)
{
this.in=in;
}
public void run()
{
while(runable){
try{
fromClient=in.readLine();
}catch(Exception e){
runable=false;
}
if(fromClient.equals("bye"))
{
System.out.println("Client exit");
runable=false;
break;
}
System.out.println("用户说: "+fromClient);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -