当前位置 : 主页 > 编程语言 > c++ >

Socket与ServerSocket——Client/Server程序

来源:互联网 收集:自由互联 发布时间:2021-06-30
通信 package hbfu.communication;import java.io.*;import java.net.*;import java.util.Scanner;public class NSocket {public static void main(String[] args) {// TODO Auto-generated method stubtry{System.out.println("本机的ip = "+InetAddres
通信
package hbfu.communication;

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class NSocket {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try{
			System.out.println("本机的ip = "+InetAddress.getLocalHost());
		}catch(UnknownHostException e){
			e.printStackTrace();
		}
		try{
			Scanner a = new Scanner(System.in);
			String ip = a.nextLine();
			int b = a.nextInt();
			Socket socket = new Socket(ip,b);
			BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
			PrintWriter os=new PrintWriter(socket.getOutputStream());
			BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
			String readline;
			readline=sin.readLine();
			while(!readline.equals("bye")){
				os.println(readline);
				System.out.println("Client:"+readline);
				System.out.println("Server:"+is.readLine());
				readline=sin.readLine();
			}
			os.close();
			is.close();
			socket.close();
		}catch(Exception e){
			System.out.println("Error"+e);
		}
	}

}




package hbfu.communication;

import java.io.*;
import java.net.*;
import java.applet.*;

public class NServer {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try{
			ServerSocket server = null;
			try{
				server = new ServerSocket(4700);
				
			}catch(Exception e){
				System.out.println("NoListen"+e);
			}
			Socket socket = null;
			try{
				socket = server.accept();
			}catch(Exception e){
				System.out.println("Error"+e);
			}
			String line;
			BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			PrintWriter os = new PrintWriter(socket.getOutputStream());
			BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
			System.out.println("Client:"+is.readLine());
			line = sin.readLine();
			while(!line.equals("bye")){
				os.println(line);
				os.flush();
				System.out.println("Server:"+line);
				System.out.println("Client:"+is.readLine());
				line = sin.readLine();
			}
			os.close();
			is.close();
			socket.close();
			server.close();
		}catch(Exception e){
			System.out.println("Error"+e);
		}
	}

}
网友评论