java之socket
socket系java中网络编程的内容。
1客户端:
package com.wtd.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;
public class TCPClint {
public static void main(String[] args) {
try {
Socket clint= new Socket("127.0.0.1", 9000);
PrintWriter pWriter = new PrintWriter(clint.getOutputStream());
pWriter.println("hello world");
pWriter.flush();
BufferedReader bReader= new BufferedReader(new InputStreamReader(clint.getInputStream()));
String line= bReader.readLine();
System.out.println(line);
clint.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2.服务器:
服务器线程:
package com.wtd.socket;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class ServerThread extends Thread {
private Socket socket;
public ServerThread(Socket socket) {
this.socket= socket;
// TODO Auto-generated constructor stub
}
@Override
public void run() {
BufferedReader bReader;
try {
bReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String text = bReader.readLine();
PrintWriter pWriter = new PrintWriter(socket.getOutputStream());
pWriter.println(text+ " from thread server");
pWriter.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally{
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
2.服务器端:
package com.wtd.socket;import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer2 {
public static void main(String[] args) {
try {
ServerSocket server= new ServerSocket(9000);
while (true) {
Socket socket= server.accept();
ServerThread serverThread= new ServerThread(socket);
serverThread.start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
执行:先执行服务器端,然后执行客户端:
output:
hello world from thread server
以上是 java之socket 的全部内容, 来源链接: utcz.com/z/391678.html