📄 socketconn.java~1~
字号:
package stock ;
import java.net.* ;
import java.io.* ;
import javax.swing.*;
public class SocketConn
{
Socket s ;
DataInputStream input ;
DataOutputStream output ;
boolean error=false;
public SocketConn()
{ //构造函数,建立与服务器的连接并与输入输出流相关
String url="202.117.55.178";
int port=6001;
try
{
this.s = new Socket(InetAddress.getByName(url), port) ;
this.input = new DataInputStream(s.getInputStream()) ;
this.output = new DataOutputStream(s.getOutputStream()) ;
}
catch (IOException ex)
{
System.out.println("socket连接失败");
this.error=true;
}
}
public SocketConn(String url, int port)
{ //构造函数,建立与服务器的连接并与输入输出流相关
try
{
this.s = new Socket(InetAddress.getByName(url), port) ;
this.input = new DataInputStream(s.getInputStream()) ;
this.output = new DataOutputStream(s.getOutputStream()) ;
}
catch (IOException ex)
{
System.out.println("socket连接失败");
this.error=true;
}
}
public void send(String s)
{ //发送字符串
try
{
ByteArrayOutputStream byteOut = new ByteArrayOutputStream() ; //该类实现一个以字节数组形式写入数据的输出流。当数据写入缓冲区时,它自动扩大
DataOutputStream out = new DataOutputStream(byteOut) ;
out.writeUTF(s) ; //以UTF的形式将消息写入out的写入目标:byteOut流
out.flush() ; //相当于写入输出流
byte buf[] = byteOut.toByteArray() ; //创建一个新分配的字节数组buf[]。尺寸为该byteOut输出流的当前尺寸,buf的内容就是当前byteOut里面的内容(皆以byte为单位)
output.write(buf) ; //将这个buf数组的内容写入output流中
output.flush() ;
//close streams
byteOut.close() ;
out.close() ;
}
catch (IOException ex)
{
System.out.println("发送数据失败");
}
}
public String getAck()
{ //得到反馈
try
{
return this.input.readUTF() ;
}
catch (IOException ex)
{
return null ;
}
}
public void close()
{ //关闭与服务器的连接
try
{
send("close..") ; //发送关闭讯息
this.input.close() ;
this.output.close() ;
this.s.close() ;
}
catch (IOException ex)
{
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -