关于socket

import java.io.IOException;

import java.io.OutputStream;

import java.io.InputStream;

import java.net.ServerSocket;

import java.net.Socket;

import java.io.DataInputStream;

import java.io.DataOutputStream;

public class firstClass {

public static void main(String[] args) throws Exception, Error {

Thread t = new MySocketServer(6789);

t.run();

}

}

//Socket服务端

class MySocketServer extends Thread{

private ServerSocket serverSocket ;

//写一个构造函数,接收端口号

public MySocketServer(int port ) throws Exception,Error{

//创建一个对象

serverSocket = new ServerSocket(port);

serverSocket.setSoTimeout(20000);//10000表示十秒

}

public void run() {

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());//读取这个in

DataOutputStream Out = new DataOutputStream (server.getOutputStream());

Out.writeUTF("hi user , I get u");

server.close();

//最后关闭server对象

}catch(IOException e) {

}

}

}

//客户端 ,通过cmd打开

import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.Socket;

public class client {

public static void main(String[] args) throws IOException {

String serverName = "localhost";

int port = 6789;

Socket client = new Socket(serverName,port);

System.out.println("服务端的主机地址是:"+ client.getRemoteSocketAddress());

//客户端的输入流是指向服务端的输出流

OutputStream outToServer = client.getOutputStream();

DataOutputStream out = new DataOutputStream(outToServer);//创建output对象

out.writeUTF("hi mr.Server");

InputStream inFormServer = client.getInputStream();

DataInputStream in = new DataInputStream(inFormServer);//创建input对象

System.out.println("服务器发回来的消息:"+ in.readUTF());

client.close();

}

}

你可能感兴趣的:(java,开发语言)