java -Socket示例程序

Socket程序,server启动,可以有多个线程向server发送信息,server收到信息后,在信息前加上“ECHO”并将内容转为大写返回。当发送“byebye”时,通信结束,关闭客户端。
serverSocket代码:

package server;

import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class SocketServer {

	private static class Mythread implements Runnable{

		private Socket client;
		
		public Mythread(Socket client) {
			this.client = client;
		}
		
		@Override
		public void run() {
			try {
				Scanner scanner = new Scanner(client.getInputStream()); // 接收客户端发来的数据。
				scanner.useDelimiter("\r\n");
				PrintStream out = new PrintStream(client.getOutputStream()); //向客户端发送消息
				boolean flag = true;
				while(flag) {
					if(scanner.hasNext()) {
						String str = scanner.next().trim();//防止有多余的空格
						System.out.println("收到一条信息");
						if ("byebye".equalsIgnoreCase(str)) {
							flag = false;
							break;
						}
						out.println("ECHO : " + str.toUpperCase());
					}
				}
				scanner.close();
				out.close();
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	public static void main(String[] args) throws IOException {
		ServerSocket server = new ServerSocket(9999); //监听端口
		System.out.println("启动成功");
		boolean flag = true;
		while(flag) {
			Socket client = server.accept();//接收连接
			
			new Thread(new Mythread(client)).start();
		}
		
		server.close();
	}

}

客户端代码:

package client;

import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

public class Client {

	public static void main(String[] args) throws Exception {
		Socket client = new Socket("127.0.0.1", 9999); //与127.0.0.1的主机的9999端口建立连接
		Scanner keyScanner = new Scanner(System.in); // 键盘输入
		keyScanner.useDelimiter("\r\n");
		Scanner netScanner = new Scanner(client.getInputStream()); //用于读取socket返回的内容
		netScanner.useDelimiter("\r\n");
		PrintStream netout = new PrintStream(client.getOutputStream()); //发送键盘内容给server
		boolean flag = true;
		while(flag) {
			System.out.println("请输入要发送的字符:");
			if (keyScanner.hasNext()) {
				String str = keyScanner.next().trim();
				netout.println(str);
				if (netScanner.hasNext()) {
					System.out.println(netScanner.next() );
				}
				if ("byebye".equalsIgnoreCase(str)) {
					flag = false;
					break;
				}
			}
		}
		keyScanner.close();
		netScanner.close();
		netout.close();
		client.close();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值