/**
*TCPServer
*/
import java.io.*
import java.net.*
class TCPServer{
public static void main(String[] args)throws IOException{
ServerSocket listen = new ServerSocket(5050)
Socket server = listen.accept()
InputStream in = server.getInputStream()
OutputStream out = server.getOutputStream()
char c = (char)in.read()
System.out.println("收到:" + c)
out.write('s')
out.close()
in.close()
server.close()
listen.close()
}
}
/**
*TCPClient
*/
import java.io.*
import java.net.*
class TCPClient{
public static void main(String[] args)throws IOException{
Socket client = new Socket("127.0.0.1" , 5050)
InputStream in = client.getInputStream()
OutputStream out = client.getOutputStream()
out.write('c')
char c = (char)in.read()
System.out.println("收到:" + c)
out.close()
in.close()
client.close()
}
}
以派基下是一个展示java使用tcp通讯的简亩闷单例子,包括尘耐谨服务器和客户端代码:\x0d\x0a\x0d\x0a/**\x0d\x0a *TCPServer\x0d\x0a */\x0d\x0aimport java.io.*\x0d\x0aimport java.net.*\x0d\x0aclass TCPServer{\x0d\x0apublic static void main(String[] args)throws IOException{\x0d\x0aServerSocket listen = new ServerSocket(5050)\x0d\x0a\x0d\x0aSocket server = listen.accept()\x0d\x0aInputStream in = server.getInputStream()\x0d\x0aOutputStream out = server.getOutputStream()\x0d\x0achar c = (char)in.read()\x0d\x0aSystem.out.println("收到:" + c)\x0d\x0aout.write('s')\x0d\x0a\x0d\x0aout.close()\x0d\x0ain.close()\x0d\x0aserver.close()\x0d\x0alisten.close()\x0d\x0a}\x0d\x0a}\x0d\x0a\x0d\x0a/**\x0d\x0a *TCPClient\x0d\x0a */\x0d\x0aimport java.io.*\x0d\x0aimport java.net.*\x0d\x0aclass TCPClient{\x0d\x0apublic static void main(String[] args)throws IOException{\x0d\x0aSocket client = new Socket("127.0.0.1" , 5050)\x0d\x0aInputStream in = client.getInputStream()\x0d\x0aOutputStream out = client.getOutputStream()\x0d\x0a\x0d\x0aout.write('c')\x0d\x0achar c = (char)in.read()\x0d\x0aSystem.out.println("收到:" + c)\x0d\x0aout.close()\x0d\x0ain.close()\x0d\x0aclient.close()\x0d\x0a}\x0d\x0a}欢迎分享,转载请注明来源:内存溢出
评论列表(0条)