首页 > 试题广场 >

在本机建立一个多线程的服务端,接收本机客户端的连接请求,当客

[问答题]

在本机建立一个多线程的服务端,接收本机客户端的连接请求,当客户端向服务端发送“Hello Java!”,服务端回复“Nice Work!”。


package Server;
// Server_Socket.java
import java.io.*;
import java.net.*;
public class Server_Socket {
public static final int PORT=6060;
public static void main(String[]args)throws IOException{
	ServerSocket s=new ServerSocket(PORT);
	try{
		Socket socket =s.accept();
		try{
			BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
			PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
			while(true){
				String str=in.readLine();
				if(str.equals("END"))
					break;
				System.out.println(str);
				out.println("Nice Work!");
			}
		}
		finally{
			socket.close();
			}
	}
	finally{
		s.close();
	}
	}
}
// Client_Socket.java
import java.net.*;
import java.io.*;
public class Client_Socket {
public static void main(String[]args)throws IOException{
	InetAddress addr=InetAddress.getByName(null);
	Socket socket=new Socket(addr,Server_Socket.PORT);
	try{
		BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
		PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
		out.println("Hello java!");
		String str=in.readLine();
		System.out.println(str);
		out.println("END");
		}
	finally{
	socket.close();
	}
}
}

发表于 2017-05-17 16:10:44 回复(0)