欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

socket通信 博客分类: java javasockettcp 

程序员文章站 2024-03-14 22:34:53
...

客户端:

package c;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {
	public static PrintWriter out;
	public static void main(String[] args) throws UnknownHostException, IOException {
		System.out.println("客户端启动............");
		Socket socket = new Socket(InetAddress.getLocalHost(),4215);
		out = new PrintWriter(socket.getOutputStream());
		BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		while(true){
			out.println(new Scanner(System.in).next());
			out.flush();
			System.out.println("服务器:"+in.readLine());
			
		}
	}
	
}

 服务器端:

package s;

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

public class Server {
	public static void main(String[] args) throws Exception {
		
		ServerSocket ss = new ServerSocket(4215);
		Socket socket = ss.accept();
		System.out.println("服务器启动");
		BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		PrintWriter out = new PrintWriter(socket.getOutputStream());
		
		while(true){
			System.out.println("客户端:"+in.readLine());
			out.println(new Scanner(System.in).next());
			out.flush();
		}
	}
}
 
相关标签: java socket tcp