java Socket客户端和服务器端

客户端:

package com.lzx.socket;

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

import org.xml.sax.InputSource;

public class SocketClient {

	public static void main(String[] args) {
		new SocketClient();
	}
	
	public SocketClient() {
		try {
			Socket socket = new Socket("127.0.0.1", 9999);
			PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
			//接收键盘输入内容
			System.out.println("enter some words : ");
			BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
			String line = reader.readLine();
			out.println(line);
			
			//接收服务器端的数据
			BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			System.out.println("reply from server : " + in.readLine());
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}


 服务器:

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) {
		new SocketServer();
	}
	
	public SocketServer() {
		try {
			ServerSocket serverSocket = new ServerSocket(9999);
			Socket socket = serverSocket.accept();
			String remoteHost = serverSocket.getInetAddress().getHostName();
			int remotePort = serverSocket.getLocalPort();//客户端端口
			System.out.println("A client come, remoteHost :" + remoteHost + ", remotePort : " + remotePort);
			//接收客户端的数据
			BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			System.out.println("received from client : " + reader.readLine());
			
			//回复客户端
			PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
			out.println("Tanks,I love you!");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}


 

上一篇:解决kindeditor上传图片、文件的错误。


下一篇:Python socket 实现服务端和客户端数据传输(TCP)