📄 server.java
字号:
import java.io.*;
import java.net.*;
public class Server implements Runnable
{
ServerSocket serverSocket;
PrintStream streamToClient;
BufferedReader streamFromClient;
Socket fromClient;
static int count=0;
Thread thread;
public Server()
{
try
{
serverSocket=new ServerSocket(1001);//create socket
}
catch(Exception e)
{
System.out.println("Socket could not be created "+e);
}
thread=new Thread(this);
thread.start();
}
public void run()
{
try
{
while (true)
{
fromClient=serverSocket.accept();//accept connection from client
count++;
System.out.println("Client connection no:"+count);
streamFromClient=new BufferedReader(new InputStreamReader((fromClient.getInputStream())));//create an input stream for the sokcet
streamToClient=new PrintStream(fromClient.getOutputStream());//create an output stream for the sokcet
String str=streamFromClient.readLine();//read the message sent by client
System.out.println("Client connection name:" + str);
streamToClient.println("Welcome "+str);//message sent message to client
}//end of while
}
catch(Exception e)
{
System.out.println("Exception "+e);
}
finally
{
try
{
fromClient.close();
}
catch(Exception e1)
{
System.out.println("Could not close connection :"+e1);
}
}
}
public static void main(String args[])
{
new Server();
}
}//end of class
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -