您的位置:首页 > 编程语言 > Java开发

java简单客户端服务端

2013-06-07 22:29 239 查看
import java.net.*;

import java.io.*;

public class Service

{

public static void main(String[] args)

{

InputStream
in = null;

OutputStream out = null;

int port
= 33333;

try {

ServerSocket ss = new ServerSocket(port);

while(true) {

Socket s = ss.accept();

System.out.println("a is connected!");

in = s.getInputStream();

out = s.getOutputStream();

DataInputStream
din = new DataInputStream(in);

DataOutputStream
dout = new DataOutputStream(out);

dout.writeUTF("Hello Client");

String s1 = null;

if ((s1=din.readUTF()) != null) {

System.out.println(s1);

System.out.println("ip address is " + s.getInetAddress());

System.out.println("the port is " + s.getPort());

}

dout.flush();

dout.close();

din.close();

s.close();

}

} catch (IOException e) {

System.out.println("the server socket is error!");

}

}

}

import java.net.*;

import java.io.*;

public class Client

{

public static void main(String[] args)

{

InputStream
in = null;

OutputStream out = null;

int port = 33333;

try {

Socket s = new Socket("localhost", port);

in = s.getInputStream();

out = s.getOutputStream();

DataInputStream din = new DataInputStream(in);

String s1 = null;

if ((s1=din.readUTF()) != null) {

System.out.println(s1);

}

DataOutputStream dout = new DataOutputStream(out);

dout.writeUTF("Hello Server !!!");

din.close();

dout.close();

s.close();

} catch (ConnectException e) {

System.out.println("the socket is connect exception !");

} catch (IOException e) {

System.out.println("the io exception is in socket!");

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐