Java 网络编程

客服端:

package lianxi;
import java.io.*;
import java.net.*;
import java.util.*;

public class GreetingClient {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String serverName = args[0];//java程序有一个主方法,是这样的public static void main(String [] args)
									//args[0]就是你用命令行编译运行java程序时,传入的第一个参数

		int port = Integer.parseInt(args[1]);//parseInt() 函数可解析一个字符串,并返回一个整数。
		try {
			System.out.println("连接到主机: " + serverName + "端口号: "+ port);
			Socket client = new Socket(serverName, port);
			/**
			 * 返回此套接字连接的端点的地址,如果未连接则返回 null。
			 */
			System.out.println("远程主机地址: " + client.getRemoteSocketAddress());
			OutputStream outToServer = client.getOutputStream();
			DataOutputStream out = new DataOutputStream(outToServer);
			
			out.writeUTF("Hello from " + client.getLocalSocketAddress());
			InputStream inFromServer = client.getInputStream();
			DataInputStream in = new DataInputStream(inFromServer);
			System.out.println("服务器响应: " + in.readUTF());
			client.close();
		} catch(IOException e) {
			e.printStackTrace();
		}
	}

}


服务器端:

package lianxi;

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

public class GreetingServer extends Thread{

	ServerSocket serverSocket;
	public GreetingServer(int port) throws IOException{
		serverSocket = new ServerSocket(port);
		serverSocket.setSoTimeout(10000);
		
	}
	public void run() {
		while(true) {
			try {
				System.out.println("等待远程连接,端口号为: " + serverSocket.getLocalPort());
				Socket server = serverSocket.accept();
				
				System.out.println("远程主机地址: " + server.getRemoteSocketAddress());
				DataInputStream in = new DataInputStream(server.getInputStream());
				System.out.println(in.readUTF());
				DataOutputStream out =  new DataOutputStream(server.getOutputStream());
				
				out.writeUTF("谢谢连接我:"+ server.getLocalSocketAddress()+ "\nGoodbye!");
				server.close();
			}catch(SocketTimeoutException s) {
				System.out.println("Socket timed out!");
				break;
			} catch(IOException e) {
				e.printStackTrace();
				break;
			}
		}
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		 int port = Integer.parseInt(args[0]);
		 try {
			 Thread t = new GreetingServer(port);
			 t.run();
		 }catch(IOException e) {
			 e.printStackTrace();
		 }
	}

}


你可能感兴趣的:(Java,java,stocket,stocket)