java socket 客户端和服务器端互相通信(聊天)

37 篇文章 0 订阅
2 篇文章 0 订阅

客户端:

package com.lzx.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class SocketClient {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		final Socket socket = new Socket("127.0.0.1", 10000);
			
		//回复服务端
		new Thread(){
			public void run() {
				try {
					PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
					BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
					String readline = in.readLine();
					System.out.println(readline);
					while(true){
						out.println(readline);
						System.out.println(" client send: " + readline);
						readline = in.readLine();
						if(readline.equals("bye"))
							break;
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			};
		}.start();
		
		
		new Thread(){
			public void run() {
				//获得客户端发来的数据
				try {
					BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
					while(true){
						System.out.println("Receive from server : " + reader.readLine());
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			};
		}.start();
		
		
	}

}


服务端:

package com.lzx.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer {

	public static void main(String[] args) throws IOException {
		ServerSocket server = new ServerSocket(10000);
		final Socket socket = server.accept();
		
		new Thread(){
			public void run() {
				//获得客户端发来的数据
				try {
					BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
					while(true){
						System.out.println("Receive from client : " + reader.readLine());
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			};
		}.start();
		
		new Thread(){
			public void run() {
				try {
					PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
					BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
					String readline = in.readLine();
					System.out.println(readline);
					while(true){
						out.println(readline);
						System.out.println(" server send: " + readline);
						readline = in.readLine();
						if(readline.equals("bye"))
							break;
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			};
		}.start();
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值