1. 程式人生 > >TCP網絡編程例子

TCP網絡編程例子

shutdown 輸入 args .sh 資源 ati 例子 != tcp網絡編程

//客戶端
package socket;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class Client001 {
public void client() {
Socket socket = null;
OutputStream os = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
//創建IP對象,指明服務器端的IP地址
InetAddress inet = InetAddress.getByName("127.0.0.1");
//1.創建Socket對象,指明服務器的ip和端口號
socket = new Socket(inet, 43333);
//2.獲取一個輸出流,用於輸出數據
os = socket.getOutputStream();
//3.寫出數據操作
os.write("你好,我是客戶端".getBytes());
//關閉數據輸出流
socket.shutdownOutput();
is = socket.getInputStream();
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[20];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
baos.write(buffer, 0, len1);

}

System.out.println(baos.toString());

} catch (IOException e) {
e.printStackTrace();

} finally {
//4.資源關閉
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}

}
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}

}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}

}
}
}


public static void main(String[] args) {
Client001 tcp = new Client001();
tcp.client();

}
}

//服務端
package socket;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServiceDem001 {
public void server() {
ServerSocket ss = null;
Socket socket = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
OutputStream os = null;
try {
//1.創建服務器端的ServeSocket,指明自己的端口號
ss = new ServerSocket(43333);
//2.調用accept()表示接受來自於客戶端的Socket;
socket = ss.accept();
//3.創建一個輸入流
is = socket.getInputStream();
//讀取輸入流中的數據
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[20];
int len;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
System.out.println(baos.toString());
System.out.println("收到了來自於:" + socket.getInetAddress().getHostName());
os = socket.getOutputStream();
os.write("你好,已收到你的信息".getBytes());


} catch (IOException e)

{
e.printStackTrace();
} finally

{
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();

}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();

}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();

}
}
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();

}

}


}
}

}

public static void main(String[] args) {
ServiceDem001 service = new ServiceDem001();
service.server();

}
}

TCP網絡編程例子