java socket 编程基础

初次学习java socket ,记此留念

server:

import java.net.*;
import java.io.*;
public class EchoMultiServerThread extends Thread{

	private Socket socket = null;
	public EchoMultiServerThread(Socket socket){
		super("EchoMultiServerThread");
		this.socket = socket;
	}
	public void run(){
		try {
			PrintWriter out = null;
			BufferedReader in = null;
			out = new PrintWriter(socket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			out.println("Hello!...");
			out.println("Enter BYE to exit");
			while (true) {
				String string = in.readLine();
				if(string == null)
					break;
				else {
					out.println("Echo: " + string);
					out.flush();
					if(string.trim().equalsIgnoreCase("BYE"))
						break;
				}
			}
			out.close();
			in.close();
			socket.close();
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
}

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

public class EchoServerThread {

	public static void main(String[] args) throws IOException {
		ServerSocket serverSocket = null;
		boolean listening  = true;
		try {
			serverSocket = new ServerSocket(1111);
			
		} catch (IOException e) {
			// TODO: handle exception
			System.err.println("Could not listen on port : 1111");
			System.exit(1);
		}
		
		while (listening) {
			//Socket socketClient = serverSocket.accept();
			System.out.println("listeing。。。");
			new EchoMultiServerThread(serverSocket.accept()).start();
		}
		serverSocket.close();
	}
}

client:

import java.io.*;
import java.net.*;
public class EchoClient {
	
	public static void main(String[] args) throws Exception{
		
		Socket echoSocket = null;
		PrintWriter out = null;
		BufferedReader in = null;
		try {
			echoSocket = new Socket("localhost", 1111);
			out = new PrintWriter(echoSocket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
		} catch (UnknownHostException e) {
			// TODO: handle exception
			System.err.println("Don't know about host: localhost.");
			System.exit(1);
		}
		System.out.println(in.readLine());
		System.out.println(in.readLine());
		
		BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
		String userInput;
		while ((userInput = stdIn.readLine()) != null) {
			out.println(userInput);
			System.out.println(in.readLine());
			if(userInput.equalsIgnoreCase("bye"))
				break;
			
		}
		out.close();
		in.close();
		echoSocket.close();
	}
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值